package com.phx.serialjni;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.phx.serialjni.BaseActivity;
import com.phx.serialjni.MeziView;
import com.phx.uart.uartJni;
import com.phx.uart.uartJnit;
import com.phx.widget.VerticalSeekBar;
import com.phx.widget.VerticalSeekBar_Reverse;
import com.phx.widget.nSeekBar;
import com.utils.CRC16;
import com.utils.TransformUtils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.Socket;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.math.MathContext;

import static com.phx.serialjni.startActivity.makeStatusBarTransparent;


 public class MainActivityf extends Activity implements SeekBar.OnSeekBarChangeListener {
     //  public class MainActivityf extends BaseActivity  {
     public static String SOCKET_ADDRESS = "com.clzk.mobilej.local";
     private SeekBar seekBar;
     private SeekBar seekBar31;
     private SeekBar seekBar32;
     private String lcommand = "";

     private SeekBar seekBar1;
     private SeekBar seekBar2;
     private SeekBar seekBar3;
     private int isSel = 0;
     private int isDown = 0;
     private int isUp = 0;
     private int isMove = 0;
     private int isCal = 0;
     private boolean nneed = false;
     private boolean isseek1feed = false;
     private boolean isseek2feed = false;
     private int firseekv = 0;
     private int isdengpressed = 0;
     private boolean isneidingon = false;
     private int lfirseekv = 102;
     private int lfirseekvt = 103;
     private int lfirseekvt1 = 103;
     private int lfirseekvt2 = 103;
     private static MainActivityf mActivity = null;
     private static WeakReference<MainActivityf> myown= null;
     ImageView pointValuea;
     ImageView pointValueb;
     boolean slidera = false;
     String headerData = "5aa5";
     byte[] read_buf = new byte[512];
     int fd;
     TextView testView;
     TextView testtView;
     TextView testfView;
     SharedPreferences userInfo;
     String messagercv;
     MeziView mezi;


     //        private  class SumHandler extends Handler {
//            private WeakReference mActivity;
//
//            public SumHandler(MainActivityf activity) {
//                mActivity = new WeakReference(activity);
//
//            }

     Handler handler = new Handler();

//             private  class SumHandler extends Handler {
//                 private WeakReference<MainActivityf> mActivity;
//
//                 public SumHandler(MainActivityf activity) {
//                     mActivity = new WeakReference<MainActivityf>(activity);
//
//                 }
//             }

     @SuppressLint("HandlerLeak")
     public Handler uHandler = new Handler(){
//     private static Handler handler = new Handler();
//     @SuppressLint("HandlerLeak")
//   //   private  Handler uHandler = new SumHandler(this);
//    // private Handler uHandler = new Handler(new Handler.Callback(){
//
//     public Handler uHandler = new Handler(){
         @Override
             public void handleMessage(Message msg) {
             super.handleMessage(msg);

             //   HandlerActivity activity = (HandlerActivity) mActivity.get();

             if(myown!=null) {
                 switch (msg.what) {
                     case 0:
                         break;


                     case 1:
                         String commandTxt = msg.getData().getString("alltext");
                         //if (commandTxt.length() > 10)

                         //
//                    if(PageS.pageno == 2)
//                    {
//                        if (commandTxt.length() > 10) {
//                            getvoltage(commandTxt);
//                        }
//                    }
//                    else
//
//                    {
//                        testtView.setText(commandTxt);
                         if (commandTxt.length() > 10) {

                             try {
                                 refreshallui(commandTxt, lcommand);
                                 lcommand = commandTxt;
                             } catch (Exception ex) {
                                 renew();
                             }

                         }
                         //  }


                         break;
                     default:
                         break;
                 }
             }
         }

};







    // private Handler uHandler = new Handler(mycall);



     private  void getvoltage(String comingdata)
     {
         // String vheaderData = "";
         String message = comingdata;
         if (comingdata.length() >= 40) {
             message = comingdata.substring(0, 40);
         }
         // String message = comingdata;
         String firstFour = message.substring(0, 4);


         int positionInBoard = 0;


         if (firstFour.equals(headerData)) {
             int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
             message = message.substring(0, msgcounts * 2 + 6);
         }
         else {
             return;
         }

         int counts = 0;
         if (message.length() > 19) {

             int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
             counts = (msgcounts - 7) / 2 + 1;

             String[] feedDevice = new String[counts];
             String[] feedStatus = new String[counts];

             if (counts == 1) {


                 String feedDevicex = message.substring(8, 12);

                 String deviceStaus = message.substring(12, 16);

                 Message msg = new Message();
                 //  if (isSend) {
                 msg.what = 2;
                 // msg.obj = deviceStaus;
                 Bundle bundle = new Bundle();
                 bundle.putString("feedDevice", feedDevicex);
                 bundle.putString("feedStatus", deviceStaus);
                 msg.setData(bundle);
                if (feedOK(feedDevicex)) {
                    PageS.feedMap.put(feedDevicex, deviceStaus);
                }
                else
                {
                    return;
                }
                 mHandler.sendMessage(msg);
             } else {
                 for (int cc = 0; cc < counts; cc++) {
                     feedDevice[cc] = TransformUtils.getAddress(message.substring(8, 12), cc);
                     feedStatus[cc] = message.substring(12 + cc * 4, 16 + cc * 4);

                     Message msg = new Message();
                     //  if (isSend) {
                     msg.what = 1;
                     Bundle bundle = new Bundle();
                     bundle.putString("feedDevice", feedDevice[cc]);
                     bundle.putString("feedStatus", feedStatus[cc]);
                     msg.setData(bundle);
                     if (feedOK(feedDevice[cc])) {
                         PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
                     }
                     else
                     {
                         return;
                     }
                     mHandler.sendMessage(msg);
                 }
             }
         }
     }
     private  boolean  checkability(String comingdata,String lcomingdata)
     {
         boolean result1 = false;
         boolean result2 = true;
         boolean result3 = true;
         boolean result = false;

         try {
             if(lcomingdata.equals(comingdata))
             {
                 return false ;
             }
             int alllength = comingdata.length() - 3;
             String firstFour = "";
             if ((comingdata.length()) > 4) {
                 firstFour = comingdata.substring(0, 4);
                 if (firstFour.equals(headerData)) {
                     int msgcounts = Integer.parseInt(comingdata.substring(4, 6), 16);
                     if (alllength == (msgcounts * 2 + 3)) {
                         result1 = true;
                     }
                     //   int countsw = (msgcounts - 7) / 2 + 1;
                     //  message = message.substring(0, countsw * 2 + 6);
                 }

                 String feedDevicex = comingdata.substring(8, 12);
                 if(!feedOK(feedDevicex))
                 {
                     result2 = false;
                 }

                 int crccounts = 0;
                 int crclength = comingdata.length();
                 int allcounts = Integer.parseInt(comingdata.substring(4, 6), 16);
                // crccounts = (allcounts - 7) / 2 + 1;
                 boolean crcbool1 = crclength >= allcounts + 3?true:false;

                 boolean crcbool2 = comingdata.substring(2, 4).equals("a5");
                 boolean crcbool3 = comingdata.substring(6, 8).equals("82");

                 String hecrc = comingdata.substring(6, 2*(allcounts-2) + 6);
            // byte[] tempByte =  TransformUtils.hexStringToBytes(hecrc);
                // byte[] tempByte =  hexString2Intger(hecrc);
            //nCRC16(tempByte,allcounts-2);
//                 char uchCRCHi = ;   //CRC高字节
//                 char uchCRCLo;   //CRC低字节
//                 tempByte[9]=(byte)(uchCRCHi);
//                 tempByte[10]=(byte)(uchCRCLo);
                // StringBuffer mcrcstr = CRC16.crc16x(hecrc);
                byte[] tmpxx =  getSendBuf(hecrc) ;
                String lastvalue = getBufHexStr(tmpxx);
               // String mcrcstr = CRC16.myCRC16(hecrc);
                // final String cmdw = allCmd.substring(0, 22);
                 String rcrcstr =  comingdata.substring(crclength-4, crclength);

                 int clen = lastvalue.length();
                 String cccstr = lastvalue.substring(clen-4, clen).toLowerCase();
                 boolean crcbool4 = rcrcstr.equals(cccstr)? true: false;
                // boolean crcbool4 = rcrcstr.equals(mcrcstr)? true: false;

//                 if((RxCounter>=RxBuffer[2]+3)&&(RxBuffer[1]==0xA5)&&(RxBuffer[3]==0x82)){
//                     RxCounter=0;
//                     CRC16(&RxBuffer[3],5);
//                     if((RxBuffer[8] == uchCRCHi) && (RxBuffer[9] == uchCRCLo))
                 result3 = crcbool1 && crcbool2 && crcbool3 && crcbool4;
             }



             result = result1 && result2 && result3;
         }
         catch(Exception ex)
         {
             //result = false;
             renew();
         }

         return result;
     }

    public  byte[] hexString2Intger(String str) {
        byte[] byteTarget = new byte[11];
        for (int i = 0; i < str.length() / 2; ++i)
            byteTarget[i] = (byte)(Integer.parseInt(str.substring(i * 2, i * 2 +2), 16) & 0xff);
        return byteTarget;
    }
    public static String getBufHexStr(byte[] raw) {
        String HEXES = "0123456789ABCDEF";
        if (raw == null) {
            return null;
        }
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(
                    HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }

    public static byte[] getSendBuf(String toSend) {
        byte[] bb = HexString2Buf(toSend);
        int ri = alex_crc16(bb, bb.length - 2);
        bb[bb.length - 2] = (byte) (0xff & ri);
        bb[bb.length - 1] = (byte) ((0xff00 & ri) >> 8);
        return bb;
    }

    public static byte[] HexString2Buf(String src) {
        int len = src.length();
        byte[] ret = new byte[len / 2 + 2];
        byte[] tmp = src.getBytes();
        for (int i = 0; i < len; i += 2) {
            ret[i / 2] = uniteBytes(tmp[i], tmp[i + 1]);
        }
        return ret;
    }

    private static byte uniteBytes(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
                .byteValue();
        _b0 = (byte) (_b0 << 4);
        byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
                .byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }
    static int alex_crc16(byte[] buf, int len) {
        int i, j;
        int c, crc = 0xFFFF;
        for (i = 0; i < len; i++) {
            c = buf[i] & 0x00FF;
            crc ^= c;
            for (j = 0; j < 8; j++) {
                if ((crc & 0x0001) != 0) {
                    crc >>= 1;
                    crc ^= 0xA001;
                } else
                    crc >>= 1;
            }
        }
        return (crc);
    }
//    public static String myCRC16c(String string) {
//
//        byte[] tempByte =  TransformUtils.hexStringToBytes(string);
//        int[] data = new int[tempByte.length + 3];// 代表指令和数据的六个字节
//       // data = {0};
//        for (int i = 0; i < tempByte.length; i++) {
//            // 将16进制数转换为int类型
//            data[i] = TransformUtils.byteToInt(tempByte[i + 3]);
//        }
//        int[] d1 = CRC16.crc(data);// CRC16校验
//        for (int i = 0; i < d1.length; i++) {
//            // 将int类型转换为16进制数
//            tempByte[i + 3] = TransformUtils.intToByte(d1[i]);
//        }
//
//        return TransformUtils.bytesToHexString(tempByte);
//    }

    int   nCRC16( byte[] buf,int Len) {
        char i;
        int j;
        char uchCRCHi;   //CRC高字节
        char uchCRCLo;   //CRC低字节


        /* CRC 高位字节值表*/
          char auchCRCHi[] = {
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
                0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
                0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
                0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
        } ;

        /* CRC 低位字节值表*/
           char auchCRCLo[] = {
                0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
                0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
                0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
                0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
                0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
                0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
                0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
                0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
                0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
                0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
                0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
                0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
                0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
                0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
                0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
                0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
                0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
                0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
                0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
                0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
                0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
                0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
                0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
                0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
                0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
                0x43, 0x83, 0x41, 0x81, 0x80, 0x40
        } ;
         uchCRCHi = 0xFF;
        uchCRCLo = 0xFF;
        for(j=0;j<Len;j++){
            i =(char)( uchCRCHi ^ ((int)(buf[j+3]&0xff)));
            uchCRCHi =(char)(uchCRCLo ^ auchCRCHi[i]);
            uchCRCLo = auchCRCLo[i];
        }
        return 1;
    }
    private  void refreshallui(String comingdata,String lcomingdata)
    {
        if(!checkability(comingdata,lcomingdata)) {
           return;
        }

        String message = "";
        Log.e("coming str:",""+comingdata);
        if (comingdata.length() >= 48) {
           message = comingdata.substring(0, 48);
         //  Log.e("coming str:",""+message);
        }
        else
        {
            message = comingdata;
        }
       // String message = comingdata;
        String firstFour ="";
       // message = "5aa515820ee1000000010000000000000000000100005d8e";
      // message = "5aa5118200d10000000100000000000000009cdf";
       // message = "5aa515820ee1000000000000000000320020000000015dob";
       //   message = "5aa515820ee1000000010000000000320020000100015dob";
        //音量是50 低音音量32  蓝牙有反馈
       // message ="5aa515820ee100000000000000000032002000010000cd";
       //  message ="5aa513820ee100010000001f0010001f001000029de3";
     //message = "5aa50782e00e00000a1d";
      //  message = "5aa515820ee1000000000038003e0038003e000000019208";
        // 音量是50 低音音量32  HDMI有反馈
        if((message.length())> 4)
{                firstFour = message.substring(0, 4);
}

                int positionInBoard = 0;


//                if (firstFour.equals(headerData)) {
//                    int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
//                    int countsw = (msgcounts - 7) / 2 + 1;
//                 //  message = message.substring(0, countsw * 2 + 6);
//                }
//                else {
//                    return;
//                }

                   int counts = 0;
                if (message.length() > 19) {

                    int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
                    counts = (msgcounts - 7) / 2 + 1;

                    String[] feedDevice = new String[counts];
                    String[] feedStatus = new String[counts];

                    if (counts == 1) {


                        String feedDevicex = message.substring(8, 12);

                        String deviceStaus = message.substring(12, 16);

                        Message msg = new Message();
                        //  if (isSend) {
                     //   msg.what = 1;
                       // .get(PageS.feedDArray[jmpPostionx]);
                        if (feedOK(feedDevicex)) {
                            String ntype = PageS.feedType.get(feedDevicex);
                            msg.what = Integer.parseInt(ntype);
                        }
                        // msg.obj = deviceStaus;
                        Bundle bundle = new Bundle();
                        bundle.putString("feedDevice", feedDevicex);
                        bundle.putString("feedStatus", deviceStaus);
                        msg.setData(bundle);
                        if (feedOK(feedDevicex)) {
                            PageS.feedMap.put(feedDevicex, deviceStaus);
                        }
                        mHandler.sendMessage(msg);
                    } else {
                        for (int cc = 0; cc < counts; cc++) {
                            feedDevice[cc] = TransformUtils.getAddress(message.substring(8, 12), cc);
                            feedStatus[cc] = message.substring(12 + cc * 4, 16 + cc * 4);

                            Message msg = new Message();
                            //  if (isSend) {
                            if (feedOK(feedDevice[cc])) {
                                String ntype = PageS.feedType.get(feedDevice[cc]);
                                msg.what = Integer.parseInt(ntype);
                            }
                          //  msg.what = 1;
                            Bundle bundle = new Bundle();
                            bundle.putString("feedDevice", feedDevice[cc]);
                            bundle.putString("feedStatus", feedStatus[cc]);
                            msg.setData(bundle);
                            if (feedOK(feedDevice[cc])) {
                                PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
                            }
                            mHandler.sendMessage(msg);
                        }
                    }
                }
    }


     public void setInitcmd(int currentPage) {
         switch (currentPage) {
             case 0:
                 sendStart("BC110000");
               //  sendStart("");
                 break;
             case 1:
                 sendStart("BC220000");
                 break;
             case  2:
                 sendStart("BC330000");
                 break;


             case  3:
                 //sendStart("BC440004");
                 psendStart("5AA50883BC440000045B00");
                 break;

             default:
                 break;
         }
     }

    private  void reciteallui(String comingdata)
    {


        String message = "";

       // String[] tmpAlla = new String[]{"d001", "f002", "d002", "f003","f00d", "f006", "f004","1010","1011","71b0","72b0","73b0"};

        int countsall = PageS.tmpAlla.length;

     for(int i=0; i < countsall ; i++) {
         Message msg = new Message();
         String feedDevicex = PageS.tmpAlla[i];
         String ntype = PageS.feedType.get(feedDevicex);
         msg.what = Integer.parseInt(ntype);
         // msg.obj = deviceStaus;
         Bundle bundle = new Bundle();
         bundle.putString("feedDevice", feedDevicex);
         String deviceStaus = "";
         if (feedOK(feedDevicex)) {
             deviceStaus = PageS.feedMap.get(feedDevicex);
         }
         bundle.putString("feedStatus", deviceStaus);
         msg.setData(bundle);

         mHandler.sendMessage(msg);

     }


        }


    SharedPreferences.OnSharedPreferenceChangeListener mListener = new SharedPreferences
            .OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            String msg = sharedPreferences.getString("user_info", "0000");
           // tv.setText("sp token:" + token);
            Log.e("coming data", "sp token:" + msg);

          //  testView.setText("okokoko");
            //String fStatus = msg.obj.toString();
//            String myjmpposition = msg.getData().getString("jmppageno");
//            jmpPostion = Integer.parseInt(myjmpposition);
//            //  String myStatus = msg.getData().getString("feedStatus");
//
//            //  pagestatus.jmpPosition = Integer.parseInt(pagestatus.cmdArray[1]);
//            //  jmpPostion = pagestatus.jmpPosition;
//
//            //      if ((currentPage!=jmpPostion)&&(TransformUtils.IsInArray(src,jmpPostion + ""))) {
//
//            if ((currentPage!=jmpPostion)&&(TransformUtils.IsInArray(src,jmpPostion + ""))) {
//
//                refreshui(jmpPostion);
//            }
        }
    };


    // MeziView mezi1;
    //  final MeziView mezi;
    // final FrameLayout frame;
    MeziView newm;
    int currentPage = 0;
    PageS pagestatus = new PageS();
    Rect currentRect = new Rect();
    int maxC = 0;
    myFrameLayout frame;




   // pagestatus.

//    public PageS getPagestatus() {
//        return pagestatus;
//    }
   // pagestatus.setInit(currentPage);
    int currentC = 0;
    GridLayout gv;
    Rect tempRect = new Rect();
    //定义16个按钮的文本
    String[] chars = new String[]{
            "7", "8", "9", "%",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            ".", "0", "=", "+"
    };

    String cmdheader = "5AA50883";
    String feedheader = "5AA5";
    static int lType = 1;


    //    氛围灯调暗	0xD1D00009
//    氛围灯调亮	0xD1F00009
//    氛围灯开关	0xD1E00009
//    阅读灯调暗	0xC1D00009
//    阅读灯调亮	0xC1F00009
//    阅读灯开关	0xC1E00009
//    右中门开关	0x08A0000A
//    左中门开关	0x07A1000A
//    右桌板关闭	0xB271000E
//    右桌板打开	0xB161000E
//    左桌板关闭	0x7271000E
//    左桌板打开	0x7161000E
    String[] lcmd1Array = {
            "D1E00009",
            "C1E00009",
            "7161000E",
            "B161000E",
            "7271000E",
            "B271000E",
            "B271000E" //电子钟 需查找

    };
    String[] lhArray = {"00d1", "00c1", "0071", "00b1", "0072", "00b2", "00b2"};
    String[] rhArray = {"0048", "0047", "004B", "004a", "00d1", "004e", "004d"};
    String[] lcmd2Array = {
            "383000",
            "373000",
            "3B3000",

    };

    String[] rcmd1Array = {
            "482000",
            "472000",
            "4B2000",

    };
    String[] rcmd2Array = {
            "483000",
            "473000",
            "4B3000",

    };


    String[] sendCmd1 = {"17201F",
            "18201F",
            "D1E000",
            "123456s",
            "123456hs",
            "123456q",
            "123456stpc",
            "any command",
            "123456pt",
            "123456rvm",
            "123456sdm"};

    String[] sendCmd2 = {"17301F",
            "18301F",
            "1234567sht",
            "123456s",
            "123456hs",
            "123456q",
            "123456stpc",
            "any command",
            "123456pt",
            "123456rvm",
            "123456sdm"};

    private static final long TIMER_INTERVAL = 100;

    private static final long TIMER_INTERVAL1 = 1;

    static BufferedReader socketBufferedReader = null;
    static PrintWriter socketPrintWriter = null;
    // private GridViewAdapter adapter;
    public int currentPosition = -1;
    String[] countries = new String[]{"电视升", "电视降", "电视电源", "DVD", "顶灯", "上氛围灯", "吧台灯", "下氛围灯", "靠背前", "靠背后", "滑轮前", "滑轮后", "脚托升", "脚托降"};
    //
//    String[] sendCmd = new String[]{"5AA508830101010002F3D5",
//            "5AA508830104010001B26C",
//            "5AA5088303010100025215",
//            "5AA508830401010002E3D4",
//            "5AA508830501010002B214",
//            "5AA5088306010100024214",
//            "5AA50883070101000213D4",
//            "5AA50883080101000223D7",
//            "5AA5088309010100027217",
//            "5AA508830A010100028217",
//            "5AA508830B01010002D3D7",
//            "5AA508830C010100026216",
//            "5AA508830803010001B89C",
//            "5AA508830102010002F391"};
//String[] sendCmd = new String[]{"5AA50883010101000473D7",
//    "5AA50883010201000543D4",
//    "5AA508830103010001B253",
//    "5AA508830104010001A3D5",
//    "5AA508830105010001F215",
//    "5AA5088301060100010215",
//    "5AA50883010701000153D5",
//    "5AA50883010801000163D6",
//    "5AA508830201010002B7D5",
//    "5AA508830202010002B791",
//    "5AA508830203010002B66D",
//    "5AA508830204010002B719",
//    "5AA508830205010002B6E5",
//    "5AA508830206010002B6A1"};
    String[] sendType = new String[]{"02", "01", "01", "01",
            "01", "01", "01", "01",
            "01", "02", "02", "02",
            "02", "02"};

    //    String[] feedCode = new String[] {"0001","0003","0005","0006",
//                                      "0007","0008","0009","0010",
//                                      "0011","0012","0013","0014",
//                                      "0008","0002"};
    String[] feedClose = new String[]{"5aa50d8200d1000000000000000034cb", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e"};
    String[] feedLight = new String[]{"5aa50d8200d1000100010000000019cb", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde"};
    String[] feedDian = new String[]{"5AA50883173001001F74E3", "5AA50883183001001F20E2", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde"};

    private List<Integer> mDatas;
    private List<Integer> feedDatas;
    private GridView mGridView;
    private Socket socket = null;
    private String content = "";
    private boolean isRun = true;
  //  private MessageBackReciver mReciver;
    private IntentFilter mIntentFilter;
    private LocalBroadcastManager mLocalBroadcastManager;
    private int newPosition = -1;
    private int jmpPostion = -1;
    ImageButton arrow1;

    ImageButton arrow2;


    public static void expandViewTouchDelegate(final View view, final int top, final int bottom,
                                               final int left, final int right) {

        ((View) view.getParent()).post(new Runnable(){
            @Override
            public void run(){
                Rect bounds = new Rect();
                view.setEnabled(true);
                view.getHitRect(bounds);

                bounds.top -= top;
                bounds.bottom += bottom;
                bounds.left -= left;
                bounds.right +=right;

                TouchDelegate touchDelegate = new TouchDelegate(bounds, view);

                if (View.class.isInstance(view.getParent())) {
                    ((View) view.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });
    }



    public  boolean feedOK(String entr)
    {
        boolean feedx = false;
       // new String[]{"0071", "0072", "0073", "0074","0075","0076","0081", "0082", "0083", "0084","0085","0086","0087","1010","1011","1012","1013","1014"};
       // String[] tmpAll = new String[]{"0071", "0072", "0073", "0074","0075","0076","0081", "0082", "0099", "0099","0099","0086","0087","1010","1011","71b0","72b0","73b0"};
      //  String[] tmpAll = new String[]{"d001", "f002", "d002", "f003","c001","c002","c003","c004","f00d", "f006", "f004","b009","b00a","1010","1011","71b0","72b0","73b0"};
        return  TransformUtils.isAvail(PageS.tmpAlla,entr);
    }

//    class MessageBackReciver extends BroadcastReceiver {
//        // private WeakReference<GridView> gridView;
//
//        public MessageBackReciver() {
//            // gridView = new WeakReference<GridView>(gv);
//        }
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            // TODO Auto-generated method stub
//            String action = intent.getAction();
//            Log.e("receiveTAG", "action");
//            String headerData = "5aa5";
//
//            if (action.equals(BackService.HEART_BEAT_ACTION)) {
//
//            } else if (action.equals(BackService.STATE_SUCCESS_ACTION)) {
//                String message = intent.getStringExtra("message");
//             //    messagercv =  messagercv.substring(0, 25);
//
//
////                runOnUiThread(new Runnable() {
////                    void run() {
////                        // do something
////                        testView.setText(messagercv);
////                    }
////                });
//
//              //  TransformUtils.comingdata = message.substring(0, 25);;
//                String firstFour = message.substring(0, 4);
//
//
//                int positionInBoard = 0;
//
//
//                if (firstFour.equals(headerData)) {
//                    int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
//                    message = message.substring(0, msgcounts * 2 + 6);
//                }
//
//                if (message.length() > 19) {
//
//                    int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
//                    int counts = (msgcounts - 7) / 2 + 1;
//
//                    String[] feedDevice = new String[counts];
//                    String[] feedStatus = new String[counts];
//
//                    //check feedDevice valid
//                 //   if(feedOK(feedDevic))
//
//                    /////////////
//
//
//
//                    //////////////
//
//                    if (counts == 1) {
//
//
//                        String feedDevicex = message.substring(8, 12);
//
//                        String deviceStaus = message.substring(12, 16);
//
//                        Message msg = new Message();
//                        //  if (isSend) {
//                        msg.what = 1;
//                        // msg.obj = deviceStaus;
//                        Bundle bundle = new Bundle();
//                        bundle.putString("feedDevice", feedDevicex);
//                        bundle.putString("feedStatus", deviceStaus);
//                        msg.setData(bundle);
//                        if(feedOK(feedDevicex))
//                        {
//                            PageS.feedMap.put(feedDevicex,deviceStaus);
//                        }
//                        mHandler.sendMessage(msg);
//                    } else {
//                        for (int cc = 0; cc < counts; cc++) {
//                            feedDevice[cc] = TransformUtils.getAddress(message.substring(8, 12), cc);
//                            feedStatus[cc] = message.substring(12 + cc * 4, 16 + cc * 4);
//
//                            Message msg = new Message();
//                            //  if (isSend) {
//                            msg.what = 1;
//                            Bundle bundle = new Bundle();
//                            bundle.putString("feedDevice", feedDevice[cc]);
//                            bundle.putString("feedStatus", feedStatus[cc]);
//                            msg.setData(bundle);
//                            if(feedOK(feedDevice[cc]))
//                            {
//                                PageS.feedMap.put(feedDevice[cc],feedStatus[cc]);
//                            }
//                            mHandler.sendMessage(msg);
//                        }
//                    }
//
//
//                    if (newPosition != -1) {
//                        //  if(sendType[newPosition].equals("01")) {
//
//                        //adapter.update(newPosition, resultStatus);
//                        //  adapter.notifyDataSetChanged();
//                        // }
//
//                    }
//                }
//
//            } else if (action.equals(BackService.STATE_FAIL_ACTION)) {
//
//            } else {
//                String message = intent.getStringExtra("message");
//
//            }
//        }
//    }
//receive
    //5aa5118200f1000000010001000000000000adff0000000000000000000000000000000000000000000000000000000000000000000000000000000000
    //send
    //5AA50883F310000E001B5D

    public boolean getFeedType(String value) {
        boolean result = false;
        String test = value.substring(12, 16);
        if (test.equals("0001")) {
            result = true;
        }
        return result;
    }

    public boolean getDeviceCode(String value) {
        boolean result = false;
        String test = value.substring(9, 10);
        if (test.equals("0001")) {
            result = true;
        }
        return result;
    }


    public boolean findFeedStatus(String value) {
        boolean result = false;
        String test = value.substring(12, 16);
        if (test.equals("0001")) {
            result = true;
        }
        return result;
    }


    public String findFeedIndexy(String test) {
        for (int i = 0; i < feedClose.length; i++) {
            //String deviceCode = getDeviceCode(sendCmd[i]);
            if (feedClose[i].equals(test)) {
                return "00" + i;
            }
        }
        for (int i = 0; i < feedLight.length; i++) {
            //String deviceCode = getDeviceCode(sendCmd[i]);
            if (feedClose[i].equals(test)) {
                return "11" + i;
            }
        }
        return "-1";
    }

    public int findNewPosition(String test) {
        for (int i = 0; i < TransformUtils.feedCode.length; i++) {
            //String deviceCode = getDeviceCode(sendCmd[i]);
            if (TransformUtils.feedCode[i].equals(test)) {
                return i;
            }
        }

        return -1;
    }

    private View getTouchTarget(View view, int x, int y) {
        View targetView = null;
        // 判断view是否可以聚焦
        ArrayList<View> TouchableViews = view.getTouchables();
        for (View child : TouchableViews) {
            if (isTouchPointInView(child, x, y)) {
                targetView = child;
                break;
            }
        }
        return targetView;
    }


    public int findFeedIndex(String test) {
        for (int i = 0; i < TransformUtils.sendCmd.length; i++) {
            String banCode = TransformUtils.sendCmd[i].substring(8, 10);
            String keyCode = TransformUtils.sendCmd[i].substring(10, 12);
            int banInt = Integer.parseInt(banCode, 16);
            int keyInt = Integer.parseInt(keyCode, 16);
            int deviceInt = (banInt - 1) * 20 + keyInt;
            String deviceCode = String.valueOf(deviceInt);
            int testInt = Integer.parseInt(test, 16);
            if (testInt == deviceInt) {
                return i;
            }

        }
        return -1;

    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {


            super.handleMessage(msg);
            // tv_msg.setText(content);
            // change GridView
            if(myown!=null) {
                switch (msg.what) {


                    case 0:

                        // Toast mToast = Toast.makeText(MainActivityf.this, "请检查网络设置", 10);
                        //  mToast.show();

                        //  isSel = false;
                        break;
                    case 1://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        try {
                            String myDevice = msg.getData().getString("feedDevice");
                            String myStatus = msg.getData().getString("feedStatus");
                            //  if (lType == 1) {
                            int myPosition = TransformUtils.findPosition(PageS.feedDArray, myDevice);
                            if (myPosition != -1) {
                                //  MeziView newm = new MeziView();
                                // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
                                //  MeziView  newm = getaddMezi(myPosition);
                                // testFeed(myPosition);
                                boolean fstt = myStatus.equals("0001") ? true : false;
                                testFeed(myPosition, fstt);
                                // Log.e("feegTag","myposition");

//                            if (myStatus.equals("0001")) {
//
//                                if(newm != null)
//                                {
//
//                                    newm.mRes = PageS.onArray[myPosition];
//                                }
//                               // ctlBtn[myPosition].setBackgroundResource(onArray[myPosition]);
//                            } else {
//                               // newm.mRes = PageS.offArray[myPosition];
//
//                                if(newm != null)
//                                {
//
//                                    newm.mRes = PageS.onArray[myPosition];
//                                }
//                               // ctlBtn[myPosition].setBackgroundResource(offArray[myPosition]);
//                            }
                                //   }
//                    } else {
//                        int myPosition = TransformUtils.findPosition(rhArray, myDevice);
//                        if (myPosition != -1) {
//                            if (myStatus.equals("0001")) {
//                                ctlBtn[myPosition].setBackgroundResource(onArray[myPosition]);
//                            } else {
//                                ctlBtn[myPosition].setBackgroundResource(offArray[myPosition]);
//                            }
//                        }
                            }
                        } catch (Exception e) {
                            renew();
                        }

                        if (isSel > 0) isSel--;
                        //  isSel = false;
                        break;
                    case 2://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        String myDevicex = msg.getData().getString("feedDevice");
                        String myStatusx = msg.getData().getString("feedStatus");
                        disv(myDevicex, myStatusx);
                        //  if (lType == 1) {
//                    int myPositionx = TransformUtils.findPosition(PageS.feedDArray, myDevicex);
//                    if (myPositionx != -1) {
//                        //  MeziView newm = new MeziView();
//                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
//                        //  MeziView  newm = getaddMezi(myPosition);
//                        // testFeed(myPosition);
//                        boolean fstt = myStatusx.equals("0001") ? true:false;
//                        testFeed(myPositionx,fstt);
//                        Log.e("feegTag","myposition");
//
//
//                    }

                        //  isSel = false;
                        break;
                    case 3:
                        String[] src = {"0", "1", "2", "3", "4", "5"};

                        //通过 Bundle传过来


                        String fStatus = msg.obj.toString();
                        String myjmpposition = msg.getData().getString("jmppageno");
                        jmpPostion = Integer.parseInt(myjmpposition);
                        //  String myStatus = msg.getData().getString("feedStatus");

                        //  pagestatus.jmpPosition = Integer.parseInt(pagestatus.cmdArray[1]);
                        //  jmpPostion = pagestatus.jmpPosition;

                        //      if ((currentPage!=jmpPostion)&&(TransformUtils.IsInArray(src,jmpPostion + ""))) {

                        if ((currentPage != jmpPostion) && (TransformUtils.IsInArray(src, jmpPostion + ""))) {

                            refreshui(jmpPostion);

                        }

                        reciteallui("");
                        if (isSel > 0) isSel--;
                        break;

                    case 4://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());
                        try {
                            String fStatusx = msg.obj.toString();
                            String myStatusa = "0001";
                            String myjmppositionx = msg.getData().getString("jmppageno");
                            int jmpPostionx = Integer.parseInt(myjmppositionx);

                            if (jmpPostionx != -1) {
                                myStatusa = PageS.feedMap.get(PageS.feedDArray[jmpPostionx]);
                                //  MeziView newm = new MeziView();
                                // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
                                //  MeziView  newm = getaddMezi(myPosition);
                                // testFeed(myPosition);
                                boolean fstt = myStatusa.equals("0001") ? false : true;
                                testFeed(jmpPostionx, fstt);
                                Log.e("feegTag4", myStatusa);

                            }
                        } catch (Exception ex) {
                            renew();
                        }

                        // isSel = false;
                        break;

                    case 5://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());
                        try {
                            String fStatusxy = msg.obj.toString();
                            String myStatusay = "0000";
                            String myjmppositionxy = msg.getData().getString("jmppageno");
                            int jmpPostionxy = Integer.parseInt(myjmppositionxy);
                            if (jmpPostionxy != -1) {
                                myStatusay = PageS.feedMap.get(PageS.feedDArray[jmpPostionxy]);
                                //  MeziView newm = new MeziView();
                                // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
                                //  MeziView  newm = getaddMezi(myPosition);
                                // testFeed(myPosition);
                                boolean fstt = myStatusay.equals("0001") ? true : false;
                                testFeed(jmpPostionxy, fstt);
                                Log.e("feegTag5", myStatusay);

                            }
                        } catch (Exception ex) {
                            renew();
                        }

                        // isSel = false;
                        break;

                    case 6://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        String myDevicex6 = msg.getData().getString("feedDevice");
                        String myStatusx6 = msg.getData().getString("feedStatus");
                        dish(myDevicex6, myStatusx6);
                        //  if (lType == 1) {
//                    int myPositionx = TransformUtils.findPosition(PageS.feedDArray, myDevicex);
//                    if (myPositionx != -1) {
//                        //  MeziView newm = new MeziView();
//                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
//                        //  MeziView  newm = getaddMezi(myPosition);
//                        // testFeed(myPosition);
//                        boolean fstt = myStatusx.equals("0001") ? true:false;
//                        testFeed(myPositionx,fstt);
//                        Log.e("feegTag","myposition");
//
//
//                    }

                        // isSel = false;
                        break;

                    case 7:
                        try {
                            // int ppp = seekBar.getProgress();
                            int which = msg.getData().getInt("whichno");


                            //  int ppp = seekBar.getProgress();
                            //  if (!slidera) {
                            sendp(seekBar, which);
                            //  }
                        } catch (Exception ex) {
                            // return;
                            renew();
                        }

                        //   int jmpPostionxy = Integer.parseInt(myjmppositionxy);
                        //  sendp(seekBar,ppp);
                        // cmdOne = s
                        //msg.obj = "cmdOne";
                        //  Bundle bundle = new Bundle();
                        //    bundle.putString("jmppageno", cmdOne);
//                    bundle.putString("feedStatus", deviceStaus);


                        if (isSel > 0) isSel--;
                        break;


                    case 8://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());
                        // String which = msg.obj.toString();
                        Integer which = msg.getData().getInt("which");
                        boolean ifif = msg.getData().getBoolean("ifif");
                        testsoFeed(which, ifif);

                        // isSel = false;
                        break;


                    case 9://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        String myDevicea = msg.getData().getString("feedDevice");
                        String myStatussa = msg.getData().getString("feedStatus");
                        //  int myPosition = TransformUtils.findPosition(PageS.feedDArray, myDevice);
                        //   if (myPosition != -1) {

                        disvol(myDevicea, myStatussa);
                        //  if (lType == 1) {
//                    int myPositionx = TransformUtils.findPosition(PageS.feedDArray, myDevicex);
//                    if (myPositionx != -1) {
//                        //  MeziView newm = new MeziView();
//                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
//                        //  MeziView  newm = getaddMezi(myPosition);
//                        // testFeed(myPosition);
//                        boolean fstt = myStatusx.equals("0001") ? true:false;
//                        testFeed(myPositionx,fstt);
//                        Log.e("feegTag","myposition");
//
//
//                    }
                    default:
                        break;

                }
            }
        }
    };

    void  odish(String device,String stat)
    {
        if(PageS.allDArray[10].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            int add = (value % 10) ;
            add = (add > 5)? 1:0;
            value = (value/10 + add) * 10;
//             float lastx = (float) 0.0;
//             lastx = (float)(value/10.0);
//             NumberFormat formatter = new DecimalFormat("0.0");

            //String formmatedFloatValue = formatter.format(lastx);
            if((value> -1) && (value < 101)) {
                //   testView.setText(formmatedFloatValue);
                if(seekBar!=null)
                {
                    seekBar.setProgress(value);
                }
            }
        }
        if(PageS.allDArray[11].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
//             float lastx = (float) 0.0;
//             lastx = (float)(value/10.0);
//             NumberFormat formatter = new DecimalFormat("0.0");

            //  int value = fir * 16 + sec;
            int add = (value % 10) ;
            add = (add > 5)? 1:0;
            value = (value/10 + add) * 10;
            //String formmatedFloatValue = formatter.format(lastx);
            if((value> -1) && (value < 101))  {
                //   testView.setText(formmatedFloatValue);
                if(seekBar1!=null)
                {
                    seekBar1.setProgress(value);
                }
            }
        }
        if(PageS.allDArray[12].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
//             float lastx = (float) 0.0;
//             lastx = (float)(value/10.0);
//             NumberFormat formatter = new DecimalFormat("0.0");

            //   int value = fir * 16 + sec;
            int add = (value % 10) ;
            add = (add > 5)? 1:0;
            value = (value/10 + add) * 10;
            //String formmatedFloatValue = formatter.format(lastx);
            if((value> -1) && (value < 101))  {
                //   testView.setText(formmatedFloatValue);
                if(seekBar2!=null)
                {
                    seekBar2.setProgress(value);
                }
            }
        }

//         if(PageS.allDArray[13].equals(device)){
//             //  int fir = Integer.parseInt(stat.substring(2,3));
//             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
//             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
//             int value = fir * 16 + sec;
////             float lastx = (float) 0.0;
////             lastx = (float)(value/10.0);
////             NumberFormat formatter = new DecimalFormat("0.0");
//
//             //String formmatedFloatValue = formatter.format(lastx);
//             if((value> -1) && (value < 101))  {
//                 //   testView.setText(formmatedFloatValue);
//                 if(seekBar3!=null)
//                 {
//                     seekBar3.setProgress(value);
//                 }
//             }
//         }
    }

     void  dish(String device,String stat)
     {
         if(PageS.allDArray[10].equals(device)){
             //  int fir = Integer.parseInt(stat.substring(2,3));
             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
             int value = fir * 16 + sec;
             if((value> -1) && (value < 101)) {

                 if(seekBar!=null)
                 {
                     seekBar.setProgress(value);
                 }
             }
         }


     }

    void  mdish(String device,String stat)
    {
        if(PageS.allDArray[10].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
//             int add = (value % 10) ;
//             add = (add > 5)? 1:0;
//             value = (value/10 + add) * 10;
//             float lastx = (float) 0.0;
//             lastx = (float)(value/10.0);
//             NumberFormat formatter = new DecimalFormat("0.0");

            //String formmatedFloatValue = formatter.format(lastx);
            if((value> -1) && (value < 101)) {
                //   testView.setText(formmatedFloatValue);
                if(seekBar!=null)
                {
                    seekBar.setProgress(value);
                }
            }
        }
        if(PageS.allDArray[11].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
//             float lastx = (float) 0.0;
//             lastx = (float)(value/10.0);
//             NumberFormat formatter = new DecimalFormat("0.0");

            //  int value = fir * 16 + sec;
//             int add = (value % 10) ;
//             add = (add > 5)? 1:0;
//             value = (value/10 + add) * 10;
            //String formmatedFloatValue = formatter.format(lastx);
            if((value> -1) && (value < 101))  {
                //   testView.setText(formmatedFloatValue);
                if(seekBar1!=null)
                {
                    seekBar1.setProgress(value);
                }
            }
        }
        if(PageS.allDArray[12].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
//             float lastx = (float) 0.0;
//             lastx = (float)(value/10.0);
//             NumberFormat formatter = new DecimalFormat("0.0");

            //   int value = fir * 16 + sec;
//             int add = (value % 10) ;
//             add = (add > 5)? 1:0;
//             value = (value/10 + add) * 10;
            //String formmatedFloatValue = formatter.format(lastx);
            if((value> -1) && (value < 101))  {
                //   testView.setText(formmatedFloatValue);
                if(seekBar2!=null)
                {
                    seekBar2.setProgress(value);
                }
            }
        }

//         if(PageS.allDArray[13].equals(device)){
//             //  int fir = Integer.parseInt(stat.substring(2,3));
//             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
//             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
//             int value = fir * 16 + sec;
////             float lastx = (float) 0.0;
////             lastx = (float)(value/10.0);
////             NumberFormat formatter = new DecimalFormat("0.0");
//
//             //String formmatedFloatValue = formatter.format(lastx);
//             if((value> -1) && (value < 101))  {
//                 //   testView.setText(formmatedFloatValue);
//                 if(seekBar3!=null)
//                 {
//                     seekBar3.setProgress(value);
//                 }
//             }
//         }
    }
     void   mania(ImageView imga,float vv)
     {
         try
         {
//
//             int x1= 273;
//             int x2=433;
//             int h1=333;
//             int h2=363;
//             int x1= 734;
//             int x2=857;
//             int h1=303;
//             int h2=323;

           //  if((vv > 10.4)&&(vv<14.6))
             if((vv > 9.9)&&(vv<14.6))
             {

//                 double xx1 =  273;
//                 double yy1 =  360;
//                 double r = 266;
//                 double halfjl = 175;
//                 int leftx = 271;
//                 int lefty= 360;
//                 int rightx = 430;
//                 int righty = 334;
//
//                 double alljd = Math.toDegrees(Math.atan(halfjl/r));
//                 double allhd = Math.toRadians(Math.atan(halfjl/r));
//               //  double bili = 0.1 * (vv-10)/10;
//                 double bili = (vv-10.4)/20.0;
//                 double nextjd = bili * alljd;
//                 double nexthd = bili * allhd;
//                 double rx = r * Math.sin(Math.toRadians(nextjd));
//                 double dx =  (int)(bili * halfjl);
//                 double gg = Math.cos(Math.toRadians(nextjd));
//
//                 double ry = r * (1 - gg);
//                 double dy =  ((int)ry);

//                 int  mx = (int)(xx1 + dx);
//                 int my = (int)(yy1 - dy);
//                 int md = (int) (0 - nextjd);

                 int seq =(int) ((vv-9.9)*10/2);
                 int mx = PageS.uarrowax[seq];
                 int my = PageS.uarroway[seq];
                 int mt = PageS.uarrowam[seq];
                 int md = 0;
                 // movePos(imga,mx,my,8,12, md);
                // movePos(imga,mx-4,my-6,8,12,md);
                 movePost(imga,mx,my,8,12,md,mt);
             }
             else
             {
                 movePos(imga,113,332-6,8,12,0);
             }

         }
         catch(Exception xx)
         {
                return;
         }

     }
    void   manib(ImageView imga,float vv)
    {
        try
        {


           // double halgrot = Math.toDegrees(Math.atan(halfjl/r));


            int x1= 734;
            int x2=857;
            int h1=303;
            int h2=323;

           // if((vv > 10.4)&&(vv<14.6))
            if((vv > 9.9)&&(vv<14.6))
            {

//                double xx1 = 734;
//               double yy1 = 332;
//                double r = 259;
//                double halfjl = 130;
//                int leftx = 739;
//                int lefty= 332;
//                int rightx = 855;
//                int righty = 308;
//
//                double alld = Math.toDegrees(Math.atan(halfjl/r));
//                double bili = (vv-10)/10.0;
//                double nextd = bili * alld;
//              //  double dx = r * Math.sin(Math.toRadians(nextd));
//                double dx =  ((vv-10) * halfjl)/10;
//                double dy = r * (1-Math.cos(Math.toRadians(nextd)));
//
//                int  mx = (int)(xx1 + dx);
//                int my = (int)(yy1 - dy);
//                int md = (int) (0 - nextd);
//
//                // movePos(imga,mx,my,8,12, md);
//                  movePos(imga,mx,my,6,9,md);
                int seq =(int) ((vv-9.9)*10/2);
               // int seq =(int) ((vv-9.9)*10/2);
                int mx = PageS.uarrowbx[seq];
                int my = PageS.uarrowby[seq];
                int mt = PageS.uarrowbm[seq];
                int md = 0;
                // movePos(imga,mx,my,8,12, md);
                // movePos(imga,mx-4,my-6,8,12,md);
                movePost(imga,mx,my,6,9,md,mt);
             //   movePost(imga,785,323,6,9,md,mt);
            }
            else {
                movePos(imga,611,309-4,6,9,0);
            }
        }
        catch(Exception xx)
        {
              return;
        }

    }

    void  disvol2(String device,String stat)
    {

        if(PageS.allDArray[23].equals(device)){
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;

            if((value > -1) && (value < 101)) {

                if(PageS.pageno == 3) {
                    isseek2feed = true;
                    seekBar2.setProgress(value);
                }


            }


        }
    }

    void  disvola(String device,String stat)
    {

        if(PageS.allDArray[23].equals(device)){
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;

            if((value > -1) && (value < 101)) {

                if(PageS.pageno == 3) {
                    isseek2feed = true;
                    seekBar2.setProgress(value);
                   // refseekbar2();
                    //createSeek32();
                }


            }


        }
    }
    void  disvol(String device,String stat)
    {
        if(PageS.allDArray[22].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;


            if((value > -1) && (value < 101)) {


                    if(PageS.pageno == 3) {

                        isseek1feed = true;
                      seekBar1.setProgress(value);

                     // isseek1feed = true;
                    }


            }

        }
        if(PageS.allDArray[23].equals(device)){
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;

            if((value > -1) && (value < 101)) {

                if(PageS.pageno == 3) {
                    isseek2feed = true;
                  //  seekBar2.invalidate();
                    seekBar2.setProgress(value);

                   // seekBar2.invalidate();
                   // refseekbar2();
                   //createSeek32();
                }


            }


        }
    }

    void  disv(String device,String stat)
     {
         if(PageS.voladdress[0].equals(device)){
           //  int fir = Integer.parseInt(stat.substring(2,3));
             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
             int value = fir * 16 + sec;
             float lastx = (float) 0.0;
             lastx = (float)(value/10.0);
             NumberFormat formatter = new DecimalFormat("00.0");

             String formmatedFloatValue = formatter.format(lastx);
             if((lastx > 9.9) && (lastx < 14.6)) {
                 if(testView == null) {

                 }
                 else {

                  if(PageS.pageno == 1) {
                      mania(pointValuea, lastx);

                      testView.setText(formmatedFloatValue);
                  }

                 }
             }
             else
             {
                 // movePos();
                // movePos(pointValuea,307,355,8,12,0);
                // mania(pointValuea,(float)14.0);
             }
         }
         if(PageS.voladdress[1].equals(device)){
             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
             int value = fir * 16 + sec;
            // int value = BigInteger(fir,16);
             float lasty = (float) 0.0;
             lasty = (float)(value/10.0);
             NumberFormat formatter = new DecimalFormat("00.0");

             String formmatedFloatValue = formatter.format(lasty);
             if((lasty > 9.9) && (lasty < 14.6)) {
                 if(testfView == null) {

                 }
                 else {
                     if(PageS.pageno == 1) {
                         manib(pointValueb, lasty);
                         testfView.setText(formmatedFloatValue);
                     }
                 }
             }
             else {
                // movePos(pointValueb,761,325,6,9,0);
                // mania(pointValueb,(float)14.0);
             }
         }
     }


     public String getNextCmd(int sseq,int interno)
     {
         String result = "";

         switch(sseq)
         {

             case 0:
                 result = "D1B000" + TransformUtils.dectostr(interno);
                 break;

             case 1:
                 result = "EE0500" + TransformUtils.dectostr(interno);
                 break;
             case 2:
                 result = "EE0600" + TransformUtils.dectostr(interno);
                 break;
             default:
                 break;

         }
         return result;
     }
    public void pslidersend(String cmdx)
    {
        //String cmdx = PageS.sliderCmd[seekno][sseq];
        // String tmpTmp = "C1200009";
        String cmdheader = "5AA50883";
        String feedheader = "5AA5";
        String allCmdx = cmdheader;
        String tmpTmp = cmdx;
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        final String cmd = allCmd.substring(0, 22);
        // String crcString = "83192001001F";
        //  String crcString =  pagestatus.cmdArray[currentPosition];
        //  String nexts = "5aa5078200030000ac1e";
        // String crcString = cmdOne ;
        //   StringBuffer exCmd = CRC16.crc16(crcString);
        new Thread() {
            public void run() {
                super.run();
                try {
                    //   if (uartJint != null) {
                    boolean isSendx = false;
                    isSendx = uartJnit.getInstance().sendCmds(cmd);
                    Log.e("send TAG", "send down: " + cmd);
                    Message msg = new Message();
                    if (isSendx) {
                        //  msg.what = 1;

                        Log.e("send TAG", "send down" + cmd + "success");
                    } else {
                        Log.e("TAG", "send down  :" + cmd + "failed!");
                    }
                    //    }
//
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep((long) TIMER_INTERVAL);
                } catch (InterruptedException e2) {
                    e2.printStackTrace();

                }
            }


        }.start();
    }
    public void slidersend(int seekno,int sseq )
    {
        String cmdx = PageS.sliderCmd[seekno][sseq];
        // String tmpTmp = "C1200009";
        String cmdheader = "5AA50883";
        String feedheader = "5AA5";
        String allCmdx = cmdheader;
        String tmpTmp = cmdx;
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        final String cmd = allCmd.substring(0, 22);
        // String crcString = "83192001001F";
        //  String crcString =  pagestatus.cmdArray[currentPosition];
        //  String nexts = "5aa5078200030000ac1e";
        // String crcString = cmdOne ;
        //   StringBuffer exCmd = CRC16.crc16(crcString);
        new Thread() {
            public void run() {
                super.run();
                try {
                    //   if (uartJint != null) {
                    boolean isSendx = false;
                    isSendx = uartJnit.getInstance().sendCmds(cmd);
                    Log.e("send TAG", "send down: " + cmd);
                    Message msg = new Message();
                    if (isSendx) {
                        //  msg.what = 1;

                        Log.e("send TAG", "send down" + cmd + "success");
                    } else {
                        Log.e("TAG", "send down  :" + cmd + "failed!");
                    }
                    //    }
//
                } catch (Exception e) {
                   // e.printStackTrace();
                    return;
                }
                try {
                    Thread.sleep((long) TIMER_INTERVAL);
                } catch (InterruptedException e2) {
                   // e2.printStackTrace();
                    return;

                }
            }


        }.start();
    }
    //数值改变

   public  String  revertValue (int value)
    {
        int fir = value/16;
        int sec = value%16;
        String res = "00";
        StringBuffer sb = new StringBuffer(res);
        sb.append(CRC16.convertF(fir));
        sb.append(CRC16.convertF(sec));
          return  sb.toString();
        //int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
        //int sec = Integer.parseInt(stat.substring(3));
       // int value = fir * 16 + sec;

    }
    @Override
//    public void onProgressChanged(SeekBar seekBarx, int progress,
//                                  boolean fromUser) {
//        // TODO Auto-generated method stub
//      //  tv1.setText("正在拖动");
//        //  testView.setText("当前数值："+progress);
//        //PageS.allDArray
//
//        int type = 0;
//        int tmp = (int) seekBarx.getTag();
//        int firpara = progress / 10 ;
////        if (feedOK(feedDevice[cc])) {
////            PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
////        }
//        String myvalue = revertValue(firpara * 10);
//                 if (feedOK(PageS.allDArray[10+tmp])) {
//             PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
//        }
//
//
//        //  testView.setText("当前数值："+ firpara);
//        if(firpara < 10) {
//         //   String cmdx = PageS.sliderCmd[tmp][firpara];
//            String cmdx = PageS.sliderCmd[tmp][firpara];
//            if (progress % 10 == 0) {
//      //          testtView.setText("当前数值：" + cmdx);
//
//                try {
//                    slidersend(tmp, firpara);
//                }
//                catch(Exception ex)
//                {
//                    return;
//                }
//            }
//        }
//
//    }


    public void onProgressChanged(SeekBar seekBarx, int progress,
                                  boolean fromUser) {
        // TODO Auto-generated method stub
        //  tv1.setText("正在拖动");
        //  testView.setText("当前数值："+progress);
        //PageS.allDArray


        int type = 0;
        int tmp = (int) seekBarx.getTag();
        // int firpara = progress  ;

        int firpara = progress / 10 ;
//        if (feedOK(feedDevice[cc])) {
//            PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
//        }
        String myvalue = revertValue(firpara * 10);
        if (feedOK(PageS.allDArray[10+tmp])) {
            PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
        }


        //  testView.setText("当前数值："+ firpara);
        if((firpara < 10)&&(firpara!=lfirseekv)) {
            //   String cmdx = PageS.sliderCmd[tmp][firpara];
            String cmdx = PageS.sliderCmd[tmp][firpara];

            // if (progress % 10 == 0) {
            //          testtView.setText("当前数值：" + cmdx);

            try {
                if(fromUser) {
                    slidersend(tmp, firpara);
                    lfirseekv = firpara;
                }
            }
            catch(Exception ex)
            {
                return;
            }
            //          }
        }

    }


    private void  sendp(SeekBar seekBarx, int progress)
    {

        int type = 0;
        int tmp = (int) seekBarx.getTag();
       // int firpara = progress / 10 ;
        int firpara = progress  ;
//        if (feedOK(feedDevice[cc])) {
//            PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
//        }
        String myvalue = revertValue(firpara * 10);
//        if (feedOK(PageS.allDArray[10+tmp])) {
//            PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
//        }


        //  testView.setText("当前数值："+ firpara);
        if(firpara < 10) {
            String cmdx = PageS.sliderCmd[tmp][firpara];
          //  if (progress % 10 == 0) {
                //          testtView.setText("当前数值：" + cmdx);

                try {
                    slidersend(tmp, firpara);
                }
                catch(Exception ex)
                {
                    return;
                }
           // }
        }
    }

    //开始拖动
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

//        try {
//            int ppp = seekBar.getProgress();
//            if(!slidera) {
//                sendp(seekBar, ppp);
//            }
//        }
//        catch(Exception e)
//        {
//
//        }
    }

    //停止拖动
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
      //  tv1.setText("停止拖动");
    }



    public void removeAll()
    {
        if (frame != null) {
            frame.removeAllViews();
            frame.invalidate();
        }
       maxC = 0;
    }

    public  void createSeekb()
    {
        seekBar = new nSeekBar(this);


//        <SeekBar
//        android:id="@+id/brseekBar"
//        android:layout_width="280dp"
//        android:layout_height="wrap_content"
//        android:layout_gravity="top|left"
//        android:layout_marginTop="300dip"
//        android:maxHeight="3dip"
//        android:minHeight="3dip"
//        android:progressDrawable="@drawable/adjust"
//        android:thumb="@drawable/thumb_image"
//        android:thumbOffset="0dip"></SeekBar>
        // seekBar.setThumb(getDrawable(R.drawable.thumb_image));
        //    Drawable drawable = getNewDrawable(MainActivityf.this,R.drawable.thumb_image, 24, 24);
        //   seekBar.setThumb(drawable);
        // Drawable draw = getResources().getDrawable(R.drawable.adjust);
        Drawable draw = getResources().getDrawable(R.drawable.adjust);
        // draw.setBounds(0,convertHn(12),0,convertHn(12));
        // draw.setBounds(0,convertHn(12),0,convertHn(12));
        // draw.setBounds(convertWn(0),convertHn(6),convertWn(403),convertHn(6));
      //  seekBar.setProgressDrawable(draw);
        seekBar.setProgressDrawable(getDrawable(R.drawable.lthumb_image));
        // seekBar.setProgressDrawable(getDrawable(R.drawable.adjust));
        //seekBar.setThumb(getDrawable(R.drawable.thumb));
        seekBar.setThumb(getDrawable(R.drawable.slider));
        // seekBar.setThumb(getDrawable(R.drawable.slider));
        // seekBar.setProgressDrawable(getDrawable(R.drawable.adjust));
        seekBar.setMinimumHeight(convertHn(0));
        //  seekBar.getThumb().setBounds();
        //  seekBar.set
        //  seekBar.setOnSeekBarChangeListener(this);
        // seekBar.setThumbOffset(0);
        //s  seekBar.setProgress(80);
        //     frame = (myFrameLayout) findViewById(R.id.gridlayout1);
        //  seekBar.buildLayer();
        // seekBar.setTop(100);
        //    seekBar.setLeft(500);
        // FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(412), convertHn(20));
        //   View headGroupView = UIUtils.inflate(mContext,R.layout.circle_head_layout);
//        RelativeLayout rlHead = (RelativeLayout)headGroupView.findViewById(R.id.rl_circle_head);
//        ImageView headImage = (ImageView)headGroupView.findViewById(R.id.iv_head_small);
        //headParams.setMargins(convertWn(566), convertHn(95), convertWn(936), convertHn(198));
        //  headParams.setMargins(convertWn(566), convertHn(95), convertWn(936), convertHn(198));
//        headParams.leftMargin = convertWn(363);
//        headParams.topMargin = convertHn(366);
        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(403), convertHn(20));

        headParams.leftMargin = convertWn(363);
        headParams.topMargin = convertHn(372);
          //headParams.topMargin = convertHn(358);
        // headGroupView.setLayoutParams(headParams);
        //  seekBar.setThumb(getDrawable(R.drawable.thumb_image));
        // headParams.height = "wrap_content";
        seekBar.setLayoutParams(headParams);
        //seekBar.setTickMark(R
        //convertWn(24), 0, convertWn(24), 0);
        seekBar.setPadding(convertWn(0), convertHn(0), convertWn(0), convertHn(0));

        seekBar.getThumb().setBounds(convertWn(402),convertHn(366),convertWn(20),convertWn(20));
        //  seekBar.getThumb().s
        // seekBar.setLayoutParams();
        seekBar.setSplitTrack(false);
        seekBar.setThumbOffset(0);
        seekBar.setMinimumHeight(convertWn(20));
        // seekBar.setLayoutDirection(1);

        //seekBar.setm
        //  seekBar.(convertHn(20));
        //      frame.addView(testView);
        frame.addView(seekBar);
        // seekBar.setPadding(500,100, 50,700);
        seekBar.bringToFront();
        // PageS.setfeeds();
//        seekBar.setTop(350);
//        seekBar.setBottom(100);
//     //   seekBar.setThumb(getDrawable(R.drawable.barseat_1_on));
//        seekBar.setThumbOffset(0);
        // seekBar.setSplitTrack(false);


      //  seekBar.setOnSeekBarChangeListener(this);
        seekBar.setOnSeekBarChangeListener(onseek);
      //  seekBar1 = new SeekBar(this);

        //seekBar.setMin(1);
        seekBar.setMax (100);
        seekBar.setKeyProgressIncrement(1);
        seekBar.setTag(0);
        //    ShapeDrawable thumb = new ShapeDrawable( new RectShape() );
//        thumb.getPaint().setColor( 0x00FF00 );
//        thumb.setIntrinsicHeight( 80 );
//        thumb.setIntrinsicWidth( 30 );
        // Drawable drawable = getNewDrawable(MainActivityf.this,R.drawable.thumb_image, 24, 24);
        //   seekBar.setThumb(drawable);
        // seekBar.setThumb(getDrawable(R.drawable.b1_off));

        //*******************
//        seekBar1.setThumb(getDrawable(R.drawable.thumb_image));
//        seekBar1.setProgressDrawable(getDrawable(R.drawable.adjust));
//        seekBar1.setMinimumHeight(convertHn(3));
//      seekBar1.setOnSeekBarChangeListener(this);
//      //seekBar1.setLeft(convertWn(32));
//      seekBar1.setPadding(convertWn(32), 0, convertWn(32), 0);
//
//        seekBar1.setThumbOffset(convertWn(32));
//        FrameLayout.LayoutParams headParams1 = new FrameLayout.LayoutParams(convertWn(376), convertHn(36));
//      //  headParams1.leftMargin = convertWn(566);
//      //  headParams1.topMargin = convertHn(193);
//        headParams1.setMargins(convertWn(566), convertHn(193), convertWn(60), convertHn(228));
//
//       // headParams1.sep
//        seekBar1.setLayoutParams(headParams1);
//        frame.addView(seekBar1);
//        // seekBar.setPadding(500,100, 50,700);
//        seekBar1.bringToFront();
//        seekBar1.setSplitTrack(false);
//        seekBar2 = new SeekBar(this);
//
//        // seekBar1.setPadding(0,0,0,0);
//        seekBar2.setThumb(getDrawable(R.drawable.thumb_image));
//        seekBar2.setProgressDrawable(getDrawable(R.drawable.adjust));
//        seekBar2.setMinimumHeight(convertHn(3));
//        seekBar2.setOnSeekBarChangeListener(this);
//        seekBar2.setThumbOffset(32);
//
//        seekBar2.setPadding(convertWn(32), 0, convertWn(32), 0);
//
//        seekBar2.setThumbOffset(convertWn(32));
//        seekBar3 = new SeekBar(this);
//
//        // seekBar1.setPadding(0,0,0,0);
//        seekBar3.setThumb(getDrawable(R.drawable.thumb_image));
//        seekBar3.setProgressDrawable(getDrawable(R.drawable.adjust));
//        seekBar3.setMinimumHeight(convertHn(3));
//        seekBar3.setOnSeekBarChangeListener(this);
//       // seekBar3.setThumbOffset(0);
//        seekBar3.setPadding(convertWn(32), 0, convertWn(32), 0);
//
//        seekBar3.setThumbOffset(convertWn(32));
//
//        seekBar.setTag(0);
//        seekBar1.setTag(1);
//        seekBar2.setTag(2);
//        seekBar3.setTag(3);
//        FrameLayout.LayoutParams headParams2 = new FrameLayout.LayoutParams(convertWn(376), convertHn(36));
//       // headParams2.setMargins(convertWn(566), convertHn(360), convertWn(936), convertHn(395));
//        headParams2.leftMargin = convertWn(566);
//        headParams2.topMargin = convertHn(293);
//        seekBar2.setLayoutParams(headParams2);
//        frame.addView(seekBar2);
//        // seekBar.setPadding(500,100, 50,700);
//        seekBar2.bringToFront();
//        seekBar2.setSplitTrack(false);
//
//        FrameLayout.LayoutParams headParams3 = new FrameLayout.LayoutParams(convertWn(376), convertHn(36));
//        // headParams2.setMargins(convertWn(566), convertHn(360), convertWn(936), convertHn(395));
//        headParams3.leftMargin = convertWn(566);
//        headParams3.topMargin = convertHn(388);
//        seekBar3.setLayoutParams(headParams3);
//        frame.addView(seekBar3);
//        // seekBar.setPadding(500,100, 50,700);
//        seekBar3.bringToFront();
//        seekBar3.setSplitTrack(false);
//************
        for (int hh=0;hh<1;hh++) {
            String tmpStat = PageS.feedMap.get(PageS.allDArray[hh+10]);
            if (!tmpStat.equals("0000")) {
                dish(PageS.allDArray[hh+10], tmpStat);
            }
        }

    }

    SeekBar.OnSeekBarChangeListener onseek = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            int type = 0;
            int tmp = (int) seekBar.getTag();
            int firpara = progress  ;

            // int firpara = progress / 10 ;
//        if (feedOK(feedDevice[cc])) {
//            PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
//        }
            // String myvalue = revertValue(firpara * 10);
            if (feedOK(PageS.allDArray[10+tmp])) {
                // PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
                PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara));
            }


            //  testView.setText("当前数值："+ firpara);
            if((firpara < 101)&&(firpara!=lfirseekv)) {
                //   String cmdx = PageS.sliderCmd[tmp][firpara];
                //  String cmdx = PageS.sliderCmd[tmp][firpara];

                String cmdx = getNextCmd(tmp,firpara);
                // if (progress % 10 == 0) {
                //          testtView.setText("当前数值：" + cmdx);

                try {
                    // if(fromUser) {
                    if (fromUser){
                        pslidersend(cmdx);

                        // slidersend(tmp, firpara);
                        lfirseekv = firpara;
                    }
                    //  }

                }
                catch(Exception ex)
                {
                    return;
                }
                //          }
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };
    SeekBar.OnSeekBarChangeListener onseek1 = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            int type = 0;
            int tmp = (int) seekBar.getTag();
            int firpara = progress  ;

            // int firpara = progress / 10 ;
//        if (feedOK(feedDevice[cc])) {
//            PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
//        }
            // String myvalue = revertValue(firpara * 10);
//            if (feedOK(PageS.allDArray[10+tmp])) {
//                // PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
//                PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara));
//            }
            if (feedOK(PageS.allDArray[22])) {
                // PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
                PageS.feedMap.put(PageS.allDArray[22], revertValue(firpara));
            }


            //  testView.setText("当前数值："+ firpara);
            if((firpara < 101)&&(firpara!=lfirseekvt1)) {
                //   String cmdx = PageS.sliderCmd[tmp][firpara];
                //  String cmdx = PageS.sliderCmd[tmp][firpara];

                String cmdx = getNextCmd(tmp,firpara);
                // if (progress % 10 == 0) {
                //          testtView.setText("当前数值：" + cmdx);

                try {


                    if (fromUser ||(!isseek1feed)){
                         pslidersend(cmdx);
                     }

                     isseek1feed = false;
                    // slidersend(tmp, firpara);
                    lfirseekvt1 = firpara;
               // }
                  //  }

                }
                catch(Exception ex)
                {
                    return;
                }
                //          }
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };
    SeekBar.OnSeekBarChangeListener onseek2o = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            int type = 0;
            int tmp = (int) seekBar.getTag();
            int firpara = progress  ;
            VerticalSeekBar_Reverse vseekBar = (VerticalSeekBar_Reverse)seekBar;
            boolean spp = vseekBar.specialTint;

            // int firpara = progress / 10 ;
//        if (feedOK(feedDevice[cc])) {
//            PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
//        }
            // String myvalue = revertValue(firpara * 10);
//            if (feedOK(PageS.allDArray[10+tmp])) {
//                // PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
//                PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara));
//            }

            if (feedOK(PageS.allDArray[23])) {
                // PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
                PageS.feedMap.put(PageS.allDArray[23], revertValue(firpara));
            }

            //  testView.setText("当前数值："+ firpara);
            if((firpara < 101)&&(firpara!=lfirseekvt2)) {
           // if(firpara < 101) {
                //   String cmdx = PageS.sliderCmd[tmp][firpara];
                //  String cmdx = PageS.sliderCmd[tmp][firpara];

                String cmdx = getNextCmd(tmp,firpara);
                // if (progress % 10 == 0) {
                //          testtView.setText("当前数值：" + cmdx);

                try {

                    // if(fromUser) {
                    if ( spp||(!isseek2feed)) {
                        pslidersend(cmdx);

                    }
                    isseek2feed = false;

                    // slidersend(tmp, firpara);
                    lfirseekvt2 = firpara;
                    // }
                    //  }

                }
                catch(Exception ex)
                {
                    return;
                }
                //          }
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };
     SeekBar.OnSeekBarChangeListener onseek2 = new SeekBar.OnSeekBarChangeListener() {
         @Override
         public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

             int type = 0;
             int tmp = (int) seekBar.getTag();
             int firpara = progress  ;
            // VerticalSeekBar_Reverse vseekBar = (VerticalSeekBar_Reverse)seekBar;
            // boolean spp = vseekBar.specialTint;

             // int firpara = progress / 10 ;
//        if (feedOK(feedDevice[cc])) {
//            PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
//        }
             // String myvalue = revertValue(firpara * 10);
//            if (feedOK(PageS.allDArray[10+tmp])) {
//                // PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
//                PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara));
//            }

             if (feedOK(PageS.allDArray[23])) {
                 // PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
                 PageS.feedMap.put(PageS.allDArray[23], revertValue(firpara));
             }

             //  testView.setText("当前数值："+ firpara);
             if((firpara < 101)&&(firpara!=lfirseekvt2)) {
                 // if(firpara < 101) {
                 //   String cmdx = PageS.sliderCmd[tmp][firpara];
                 //  String cmdx = PageS.sliderCmd[tmp][firpara];

                 String cmdx = getNextCmd(tmp,firpara);
                 // if (progress % 10 == 0) {
                 //          testtView.setText("当前数值：" + cmdx);

                 try {

                     // if(fromUser) {
                          if (fromUser ||(!isseek2feed)){
                    // if ( spp||(!isseek2feed)) {
                         pslidersend(cmdx);

                     }
                     isseek2feed = false;

                     // slidersend(tmp, firpara);
                     lfirseekvt2 = firpara;
                     // }
                     //  }

                 }
                 catch(Exception ex)
                 {
                     return;
                 }
                 //          }
             }

         }

         @Override
         public void onStartTrackingTouch(SeekBar seekBar) {

         }

         @Override
         public void onStopTrackingTouch(SeekBar seekBar) {

         }
     };

    public void refseekbar2()
    {
        if(seekBar2!=null) {
            frame.removeView(seekBar2);


            seekBar2 = null;
        }
        createSeek32a();

    }

    public  void createSeek32a()
    {
        seekBar2 = new VerticalSeekBar_Reverse(this);
        // seekBar2 = new SeekBar(this);

        // seekBar2.setTag(2);
        Drawable draw = getResources().getDrawable(R.drawable.d8);

        seekBar2.setProgressDrawable(getDrawable(R.drawable.thumb_image32));

        //   seekBar2.setThumb(getDrawable(R.drawable.d11));
        seekBar2.setThumb(getDrawable(R.drawable.d9));

        seekBar2.setMinimumHeight(convertHn(0));

        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(25), convertHn(257));

        headParams.leftMargin = convertWn(723);
        headParams.topMargin = convertHn(118);
        // headParams.topMargin = convertHn(108);

        seekBar2.setLayoutParams(headParams);

        seekBar2.setPadding(0, 0, 0, 0);

        seekBar2.setSplitTrack(false);
        seekBar2.setThumbOffset(convertWn(0));
        //      frame.addView(testView);
        frame.addView(seekBar2);
        // seekBar.setPadding(500,100, 50,700);
        seekBar2.bringToFront();
        // seekBar2.setOnSeekBarChangeListener(this);

        //seekBar.setMin(1);

        seekBar2.setMax (100);
        // seekBar2.setKeyProgressIncrement(10);
        seekBar2.setKeyProgressIncrement(1);
        seekBar2.setTag(2);

//        for (int hh=2;hh<3;hh++) {
//            String tmpStat = PageS.feedMap.get(PageS.allDArray[hh+10]);
//            if (!tmpStat.equals("0000")) {
//                dish(PageS.allDArray[hh+10], tmpStat);
//            }
//        }

        String tmpStat = PageS.feedMap.get(PageS.allDArray[23]);

        disvola(PageS.allDArray[23], tmpStat);


//        SeekBar.OnSeekBarChangeListener onseek = new SeekBar.OnSeekBarChangeListener() {
//            @Override
//            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//
//                int type = 0;
//                int tmp = (int) seekBar.getTag();
//                 int firpara = progress  ;
//
//               // int firpara = progress / 10 ;
////        if (feedOK(feedDevice[cc])) {
////            PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
////        }
//               // String myvalue = revertValue(firpara * 10);
//                if (feedOK(PageS.allDArray[10+tmp])) {
//                   // PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
//                    PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara));
//                }
//
//
//                //  testView.setText("当前数值："+ firpara);
//                if((firpara < 100)&&(firpara!=lfirseekvt)) {
//                    //   String cmdx = PageS.sliderCmd[tmp][firpara];
//                  //  String cmdx = PageS.sliderCmd[tmp][firpara];
//
//                    String cmdx = getNextCmd(tmp,firpara);
//                    // if (progress % 10 == 0) {
//                    //          testtView.setText("当前数值：" + cmdx);
//
//                    try {
//                        pslidersend(cmdx);
//
//                           // slidersend(tmp, firpara);
//                            lfirseekvt = firpara;
//
//                    }
//                    catch(Exception ex)
//                    {
//                        return;
//                    }
//                    //          }
//                }
//
//            }
//
//            @Override
//            public void onStartTrackingTouch(SeekBar seekBar) {
//
//            }
//
//            @Override
//            public void onStopTrackingTouch(SeekBar seekBar) {
//
//            }
//        };

        seekBar2.setOnSeekBarChangeListener(onseek2);

    }

    public  void createSeek32()
    {
       // seekBar2 = new VerticalSeekBar_Reverse(this);
        seekBar2 = new nSeekBar(this);
       // seekBar2 = new SeekBar(this);

       // seekBar2.setTag(2);
        Drawable draw = getResources().getDrawable(R.drawable.d8);

        seekBar2.setProgressDrawable(getDrawable(R.drawable.thumb_image32));

     //   seekBar2.setThumb(getDrawable(R.drawable.d11));
        seekBar2.setThumb(getDrawable(R.drawable.d9));

        seekBar2.setMinimumHeight(convertHn(0));

        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(247), convertHn(25));

        headParams.leftMargin = convertWn(299);
        headParams.topMargin = convertHn(324);
       // headParams.topMargin = convertHn(108);

        seekBar2.setLayoutParams(headParams);

        seekBar2.setPadding(0, 0, 0, 0);

        seekBar2.setSplitTrack(false);
        seekBar2.setThumbOffset(convertWn(0));
        //      frame.addView(testView);
        frame.addView(seekBar2);
        // seekBar.setPadding(500,100, 50,700);
        seekBar2.bringToFront();
       // seekBar2.setOnSeekBarChangeListener(this);

        //seekBar.setMin(1);

        seekBar2.setMax (100);
       // seekBar2.setKeyProgressIncrement(10);
        seekBar2.setKeyProgressIncrement(1);
       seekBar2.setTag(2);

//        for (int hh=2;hh<3;hh++) {
//            String tmpStat = PageS.feedMap.get(PageS.allDArray[hh+10]);
//            if (!tmpStat.equals("0000")) {
//                dish(PageS.allDArray[hh+10], tmpStat);
//            }
//        }

        String tmpStat = PageS.feedMap.get(PageS.allDArray[23]);

            disvol(PageS.allDArray[23], tmpStat);


//        SeekBar.OnSeekBarChangeListener onseek = new SeekBar.OnSeekBarChangeListener() {
//            @Override
//            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//
//                int type = 0;
//                int tmp = (int) seekBar.getTag();
//                 int firpara = progress  ;
//
//               // int firpara = progress / 10 ;
////        if (feedOK(feedDevice[cc])) {
////            PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
////        }
//               // String myvalue = revertValue(firpara * 10);
//                if (feedOK(PageS.allDArray[10+tmp])) {
//                   // PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
//                    PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara));
//                }
//
//
//                //  testView.setText("当前数值："+ firpara);
//                if((firpara < 100)&&(firpara!=lfirseekvt)) {
//                    //   String cmdx = PageS.sliderCmd[tmp][firpara];
//                  //  String cmdx = PageS.sliderCmd[tmp][firpara];
//
//                    String cmdx = getNextCmd(tmp,firpara);
//                    // if (progress % 10 == 0) {
//                    //          testtView.setText("当前数值：" + cmdx);
//
//                    try {
//                        pslidersend(cmdx);
//
//                           // slidersend(tmp, firpara);
//                            lfirseekvt = firpara;
//
//                    }
//                    catch(Exception ex)
//                    {
//                        return;
//                    }
//                    //          }
//                }
//
//            }
//
//            @Override
//            public void onStartTrackingTouch(SeekBar seekBar) {
//
//            }
//
//            @Override
//            public void onStopTrackingTouch(SeekBar seekBar) {
//
//            }
//        };

        seekBar2.setOnSeekBarChangeListener(onseek2);

    }

    private void createbtns()
    {
        Button xbtn =  createxButton(100);
        		xbtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
			seekBar2.setProgress(0);
			}
		});
        		frame.addView(xbtn);
    }

    protected Button createxButton(int index){
        final Button btn=new Button(this);
        btn.setId(index);
        Log.e("da","id is" + btn.getId());

        btn.setVisibility(View.VISIBLE);
        btn.setEnabled(true);


        FrameLayout.LayoutParams bheadParams = new FrameLayout.LayoutParams(convertWn(42), convertHn(42));

        bheadParams.leftMargin = convertWn(320);
        bheadParams.topMargin = convertHn(118);

        btn.setBackground(getDrawable(R.drawable.button_select));
        btn.setLayoutParams(bheadParams);
        //seekBar.setTickMark(R
        //convertWn(24), 0, convertWn(24), 0);
        btn.setPadding(convertWn(0), convertHn(0), convertWn(0), convertHn(0));

        //btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        //btn.setText("okc");
        return btn;
    }
    public  void createSeek31()
    {
        seekBar1 = new nSeekBar(this);
      //  seekBar1 = new VerticalSeekBar(this);

        Drawable draw = getResources().getDrawable(R.drawable.d8);

        seekBar1.setProgressDrawable(getDrawable(R.drawable.thumb_image31));

      //  seekBar1.setThumb(getDrawable(R.drawable.thumb_image31));
        seekBar1.setThumb(getDrawable(R.drawable.d9));

        seekBar1.setMinimumHeight(convertHn(0));

        //FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(247), convertHn(25));
        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(247, 25);

        headParams.leftMargin = convertWn(299);
      //  headParams.topMargin = convertHn(136);
        headParams.topMargin = convertHn(141);

        seekBar1.setLayoutParams(headParams);

      //  seekBar1.setPadding(convertWn(0), convertHn(7), convertWn(0), convertHn(7));

        seekBar1.setPadding(convertWn(0), 0, 0, 0);
        seekBar1.setSplitTrack(false);
        seekBar1.setThumbOffset(convertWn(0));
        //      frame.addView(testView);
        frame.addView(seekBar1);
        // seekBar.setPadding(500,100, 50,700);
        seekBar1.bringToFront();
        seekBar1.setMax (100);
        seekBar1.setKeyProgressIncrement(1);

        seekBar1.setTag(1);
      //  seekBar1.setOnSeekBarChangeListener(this);

        seekBar1.setOnSeekBarChangeListener(onseek1);
//************
//        for (int hh=1;hh<2;hh++) {
//
//            String tmpStat = PageS.feedMap.get(PageS.allDArray[hh+10]);
//            if (!tmpStat.equals("0000")) {
//                dish(PageS.allDArray[hh+10], tmpStat);
//            }
//       }
        String tmpStat = PageS.feedMap.get(PageS.allDArray[22]);
       // if (!tmpStat.equals("0000")) {
            disvol(PageS.allDArray[22], tmpStat);
       // }

    }

     public BitmapDrawable getNewDrawable(Activity context, int restId, int  dstWidth, int dstHeight){
         Bitmap Bmp = BitmapFactory. decodeResource(context.getResources(), restId);
         Bitmap bmp = Bmp.createScaledBitmap(Bmp, dstWidth, dstHeight, true);
         BitmapDrawable d = new BitmapDrawable(bmp);
         Bitmap bitmap = d.getBitmap();
         if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
             d.setTargetDensity(context.getResources().getDisplayMetrics());
         }
         return d;
     }


    public int convertHn(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);


        int jieh = getNavigationBarHeight(this);
        int screenWidthx = dm.widthPixels;
        int screenHeighty = dm.heightPixels;
//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels - jieh;
        int screenWidth = PageS.pwidth;
        int screenHeight = PageS.pheight;

        int newx = (old * screenHeight) / 600;

        return newx;

    }


    public int convertWn(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);




        int jieh = getNavigationBarHeight(this);
//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels - jieh;
        int screenWidth = PageS.pwidth;
        int screenHeight = PageS.pheight;

        int newx = oldx * screenWidth / 1024;

        return newx;

    }

    void refreshui(int keyy)
    {
        //remove old

        removeAll();

        pagestatus.setInit(keyy);

        currentPage = PageS.pageno;
        //pagestatus.allRect = pa
        //invoke event
         mezi = new MeziView(MainActivityf.this);
        //为我们的萌妹子添加触摸事件监听器
        // mezi.setOnTouchListener(new OnTouchListener() {
        //  @Override
        // public boolean onTouch(View view, MotionEvent event) {
        //设置妹子显示的位置

        mezi.bitmapX = 100;
        mezi.bitmapY = 100;
//        mezi.mleft = convertW(0);
//        mezi.mtop = convertH(0);
//        mezi.mwidth = convertW(10);
//        mezi.mheight = convertH(10);

        mezi.mleft = convertWn(0);
        mezi.mtop = convertHn(0);
        mezi.mwidth = convertWn(10);
        mezi.mheight = convertHn(10);
       // mezi.mRes = R.drawable.b2_off;
        mezi.type = 1;
       // mezi.setVisibility(View.INVISIBLE);
        mezi.setClickable(true);
        String allCmdx = cmdheader;
        String tmpTmp = "C1200009";
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        // mezi.setTag(allCmd.toString());
        mezi.setId(0);
        // frame.setTag(allCmd.toString());
        mezi.setOnTouchListener(new TouchListenerx());
       // expandViewTouchDelegate(mezi,0,0,0,0);
       // frame.setClickable(false);

        frame.setEnabled(false);
        frame.addView(mezi,-1);
        frame.setBackgroundResource(PageS.pageback);
     //   frame.setBackgroundResource(R.drawable.a6);
       // frame.addView(mezi,0);
       // frame.invalidate();

        addmezis();
       //
        if(keyy == 0) {
            createSeekb();
        }
        if(keyy == 1) {
            createV();
        }

        if(keyy == 3) {
          createSeek31();
            createSeek32();
           // createbtns();
        }
       //  getaddMezi(5);
        // frame.addView(mezi,maxC);

       // testFeed(5);
       // frame.addView(mezi,1);
        //// add feed status

        /// add original icon for feed type  19 ?
        /// rect mingan for diandong type 16 ?


        //frame.addV
       // pagestatus.setInit(currentPage);
        //addnews setid
        //findallrects
        //getcurrent
       // currentRect =

        setInitcmd(keyy);
    }


    public  void createV()
    {
        testfView = new TextView(this);

//      double value = 125.0;
//       float lastys = (float)(value/10.0);
//        NumberFormat formatter = new DecimalFormat("00.0");
//
//        String formmatedFloatValue = formatter.format(lastys);
     //   testfView.setText(formmatedFloatValue);


        testfView.setText("0.0");

        pointValuea = new ImageView(this);

        //pointValuea.setPadding(convertWn(300), convertHn(176), convertWn(352), convertHn(278));
        pointValuea.setImageDrawable(getDrawable(R.drawable.e1));


        pointValueb = new ImageView(this);

        // pointValueb.setPadding(convertWn(197), convertHn(176), convertWn(352), convertHn(278));
        pointValueb.setImageDrawable(getDrawable(R.drawable.e2));



        String tmpStat = PageS.feedMap.get(PageS.allDArray[9]);
        if(!tmpStat.equals("0000"))
        {
            disv(PageS.allDArray[9],tmpStat);

        }
        else
        {
            // mania(pointValuea,(float)10.5);

            if(PageS.pageno == 1)   manib(pointValueb,(float)0.0);
        }

        Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
        testfView.setTypeface(typeface);//第一句话“离离原上草，一岁一枯荣”引入lanti.ttf字体库

        testfView.setTextColor(getResources().getColor(R.color.colorPrimary));
        // testfView.setTextSize(158);
        // testfView.setTextSize(79);
        // testfView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 108);
        testfView.setTextSize(128);
        testfView.setGravity(Gravity.CENTER);
        //    testfView.setGravity(Gravity.RIGHT);

        testfView.setText("0.0");
        int mWidth = testfView.getMeasuredWidth();
        int mHeight = testfView.getMeasuredHeight();
//        FrameLayout.LayoutParams paramsf=new FrameLayout.LayoutParams(convertWn(149),convertHn(86));
//      //  paramsf.leftMargin = convertWn(687) + mWidth/2 ;
//     //   paramsf.topMargin = convertHn(186) +  mHeight / 2;
//        paramsf.leftMargin = convertWn(671)   ;
//        paramsf.topMargin = convertHn(175)   ;

//         FrameLayout.LayoutParams paramsf=new FrameLayout.LayoutParams(convertWn(162),convertHn(88));
//
//        paramsf.leftMargin = convertWn(624)   ;
//        paramsf.topMargin = convertHn(173)   ;
        FrameLayout.LayoutParams paramsf=new FrameLayout.LayoutParams(convertWn(174),convertHn(118));

        paramsf.leftMargin = convertWn(655)   ;
        paramsf.topMargin = convertHn(150)   ;

        testfView.setLayoutParams(paramsf);
        frame.addView(testfView,paramsf);
        //    frame.addView(testfView);
        testView = new TextView(this);
        // testView.setMargins(convertWn(566), convertHn(268), convertWn(936), convertHn(303));
        //  testView.setPadding(convertWn(187), convertHn(176), convertWn(422), convertHn(278));
        // testView.setPadding(187, 156, 422, 278);
         testView.setText("0.0");
      //  testView.setText("1" + "2.5");
        testView.setGravity(Gravity.CENTER);
        String ftmpStat = PageS.feedMap.get(PageS.allDArray[8]);
        if(!ftmpStat.equals("0000"))
        {
            disv(PageS.allDArray[8],ftmpStat);
        }
        else
        {
            if(PageS.pageno == 1) mania(pointValuea,(float)0.0);

            // manib(pointValueb,(float)10.5);
        }

        //   Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
        testView.setTypeface(typeface);//第一句话“离离原上草，一岁一枯荣”引入lanti.ttf字体库

        testView.setTextColor(getResources().getColor(R.color.colorPrimary));
        // testView.setTextSize(232);
        testView.setTextSize(180);


        //   LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        FrameLayout.LayoutParams params=new FrameLayout.LayoutParams( convertWn(302),convertHn(198));

//        params.leftMargin = convertWn(187) + tWidth/2 ;
//        params.topMargin = convertHn(166) +  tHeight / 2;
        params.leftMargin = convertWn(130)  ;
        params.topMargin = convertHn(100)  ;
        testView.setLayoutParams(params);
        // this.addContentView(testView,params);
       // testView.setText("12".concat(".5"));
        frame.addView(testView,params);
        //   MainActivityw.AsyncTaskRunner runner = new MainActivityw.AsyncTaskRunner();
        //String sleepTime = "10:0000000123456";
        //  runner.execute();

    }

    //返回键退出程序
   //  @Override
//     public boolean onKeyDown(int keyCode, KeyEvent event) {
//         if (keyCode == KeyEvent.KEYCODE_BACK
//                 && event.getAction() == KeyEvent.ACTION_DOWN) {
////            for (Activity activity : ParameterSetActivity.activityList) {
////                activity.finish();
////            }
//             this.finish();
//             System.exit(0);
//             return true;
//         }
//         return super.onKeyDown(keyCode, event);
//     }

    private void movePos(ImageView  Valueb,int x,int y,int w,int h,float d)

    {
        if (Valueb.getParent() == frame)
        {
            frame.removeView(Valueb);
        }
       // pointValueb.setRotation(d);
        //   Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");

        FrameLayout.LayoutParams paramsb=new FrameLayout.LayoutParams( convertWn(w),convertHn(h));

        paramsb.leftMargin = convertWn(x)  ;
        paramsb.topMargin = convertHn(y)  ;

        // FrameLayout.LayoutParams paramsb=new FrameLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        Valueb.setLayoutParams(paramsb);
        // this.addContentView( pointValueb,params);
        frame.addView(Valueb,paramsb);
       // Valueb.setPivotX(convertWn(x+w/2));
      //  Valueb.setPivotY(convertHn(y+h/2));
       // Valueb.setRotation(d);
       // Valueb
    }

    private void movePost(ImageView  Valueb,int x,int y,int w,int h,float d,int t)

    {
        if (Valueb.getParent() == frame)
        {
            frame.removeView(Valueb);
        }
        // pointValueb.setRotation(d);
        //   Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");

        FrameLayout.LayoutParams paramsb=new FrameLayout.LayoutParams( convertWn(w),convertHn(h));

        paramsb.leftMargin = convertWn(x)  ;
        paramsb.topMargin = convertHn(y)  ;
        Valueb.setImageDrawable(getDrawable(t));

        // FrameLayout.LayoutParams paramsb=new FrameLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        Valueb.setLayoutParams(paramsb);
        // this.addContentView( pointValueb,params);
        frame.addView(Valueb,paramsb);

    }


    public  void addmezis()
    {


        Rect tmprect = new Rect() ;
        Rect tmprecto = new Rect() ;
        int tmp =PageS.allRect.length;
        maxC = tmp ;
        for (int w=0; w<tmp;w++) {
           // tmprecto = convertRect(PageS.allRect[w]);


            tmprecto = PageS.allRect[w];
            MeziView mezii = new MeziView(MainActivityf.this);

          //  mezii.setOnTouchListener(new TouchListenerx());
            // mezi.setOnTouchListener(new OnTouchListener() {
            //  @Override
            // public boolean onTouch(View view, MotionEvent event) {


          //  expandViewTouchDelegate(mezii,0,0,0,0);
          //  mezi.bitmapX = 100;
          //  mezi.bitmapY = 0;
//            mezii.mleft = convertW(tmprecto.left);
//            mezii.mtop = convertH(tmprecto.top);
//            mezii.mwidth = convertW(tmprecto.width());
//            mezii.mheight = convertH(tmprecto.height());

            mezii.mleft = convertWn(tmprecto.left);
            mezii.mtop = convertHn(tmprecto.top);
            mezii.mwidth = convertHn(tmprecto.width());
          //  mezii.mheight = convertHn(tmprecto.height());

            mezii.mheight = convertHn(tmprecto.height());

            mezii.mRes = PageS.offArray[w];
            String addr = PageS.feedDArray[w];
            boolean bool1 = PageS.feedMap.containsKey(addr);
            String tmpS = PageS.feedMap.get(addr);
            boolean bool2 = (tmpS == null)? false:(tmpS.equals("0001"));


            mezii.type = PageS.nodeArray[w];
         //   mezii.setClickable(true);
            String allCmdx = cmdheader;
            String tmpTmp = "C1200009";
            // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
            allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
            StringBuffer allCmd = CRC16.crc16x(allCmdx);
            // mezi.setTag(allCmd.toString());
            mezii.setId(w + 1);
            // frame.setTag(allCmd.toString());
            // mezii.setOnTouchListener(new TouchListenerx());

            //  frame.addView(mezi,0);
          //  frame.setBackgroundResource(pagestatus.pageback);
           // frame.addView(mezii);
            frame.addView(mezii,w);
            if(bool1 && bool2)
            {
                mezii.mRes = PageS.onArray[w];
                mezii.repaint();
                //testFeed(w,true);
            }
          //  testFeed(6);
           // frame.getChildAt()
        }
    }

    private  void testsoFeed(int myPosition,boolean onff)
    {
        if(myPosition > 0) {
            newm = (MeziView) frame.getChildAt(myPosition );


            String aaaa = newm.getId() + "|" + myPosition;
            Log.e("feedTest", aaaa);

            if (newm != null) {
                if(onff) {
                    // newm.mleft = convertWn(0);
                    //  newm.mtop = convertHn(0);
                    //  newm.lv = 92;
                    //  newm.mwidth = convertWn(78);
                    //   newm.mheight = convertHn(78);
                    newm.mRes  = onff ? PageS.onArray[myPosition] : PageS.offArray[myPosition];
//                    newm.ho = 27;
//                    newm.lv = 116;
//                    newm.la = 242;
//                    newm.li = 255;
//                     newm.mleft = (int) (newm.mleft - 10);
//                     newm.mtop = (int) (newm.mtop -10);
//                      // newm.lv = 92;
//                     newm.mwidth = (int) (newm.mwidth +20);
//                     newm.mheight = (int) (newm.mheight +20);
                }
                else
                {
                    // newm.mleft = convertWn(0);
                    //  newm.mtop = convertHn(0);
//                    newm.ho = 255;
//                    newm.lv = 255;
//                    newm.la = 255;
//                    newm.li = 255;
//                     newm.mleft =  (int) (newm.mleft + 10);
//                     newm.mtop = (int) (newm.mtop + 10);
//                     // newm.lv = 92;
//                     newm.mwidth = (int) (newm.mwidth -20);
//                     newm.mheight = (int) (newm.mheight -20);
                    //= convertWn(91);
                    //   newm.mheight = convertHn(91);
                    newm.mRes  = onff ? PageS.onArray[myPosition] : PageS.offArray[myPosition];
                }
                // newm.mRes = onff ? PageS.onArray[myPosition] : PageS.offArray[myPosition];
                // newm.mRes = R.drawable.cbbm_television;
                newm.repaint();
                // newm.postInvalidate();
                // newm.notify();
            }
        }
      //  if(isSel>0)   isSel--;
    }



    private  void testsFeed(int myPosition,boolean onff)
     {
         if(myPosition > 0) {
             newm = (MeziView) frame.getChildAt(myPosition );


             String aaaa = newm.getId() + "|" + myPosition;
             Log.e("feedTest", aaaa);

             if (newm != null) {
                 if(onff) {
                    // newm.mleft = convertWn(0);
                   //  newm.mtop = convertHn(0);
                   //  newm.lv = 92;
                   //  newm.mwidth = convertWn(78);
                   //   newm.mheight = convertHn(78);
                     newm.ho = 27;
                     newm.lv = 116;
                     newm.la = 242;
                     newm.li = 255;
//                     newm.mleft = (int) (newm.mleft - 10);
//                     newm.mtop = (int) (newm.mtop -10);
//                      // newm.lv = 92;
//                     newm.mwidth = (int) (newm.mwidth +20);
//                     newm.mheight = (int) (newm.mheight +20);
                 }
                 else
                 {
                    // newm.mleft = convertWn(0);
                   //  newm.mtop = convertHn(0);
                     newm.ho = 255;
                     newm.lv = 255;
                     newm.la = 255;
                     newm.li = 255;
//                     newm.mleft =  (int) (newm.mleft + 10);
//                     newm.mtop = (int) (newm.mtop + 10);
//                     // newm.lv = 92;
//                     newm.mwidth = (int) (newm.mwidth -20);
//                     newm.mheight = (int) (newm.mheight -20);
                     //= convertWn(91);
                  //   newm.mheight = convertHn(91);
                 }
                 // newm.mRes = onff ? PageS.onArray[myPosition] : PageS.offArray[myPosition];
                 // newm.mRes = R.drawable.cbbm_television;
                 newm.repaint();
                 // newm.postInvalidate();
                 // newm.notify();
             }
         }
     }

    private  void testseekFeed(int myPosition,boolean onoff)
    {
        if(isdengpressed == 1) {
            int prog = onoff?50:0;
            if(seekBar!=null)
            seekBar.setProgress(prog);
            nneed = true;
            isdengpressed = 0;
        }
    }
    private  void testFeed(int myPosition,boolean onff)
    {
        try {
            {

              //  if ((myPosition > 4)&&(myPosition < PageS.nodeArray.length + 1)) {

                if (myPosition > 0)  {
                    // if((PageS.pageno == 0)&&(myPosition ==4))
                    if ((PageS.pageno == 0) && (isdengpressed == 1)) {
                        testseekFeed(myPosition, onff);
                    }

                    View tmpView = frame.getChildAt(myPosition);
                    if((tmpView!=null)&&(tmpView instanceof  MeziView))
                    {
                        newm = (MeziView) frame.getChildAt(myPosition);
                    }


                   // String aaaa = newm.getId() + "|" + myPosition;
                  //  Log.e("feedTest", aaaa);

                    if (newm != null) {

                        newm.mRes = onff ? PageS.onArray[myPosition] : PageS.offArray[myPosition];
                        // newm.mRes = R.drawable.cbbm_television;
                        newm.repaint();
                        // newm.postInvalidate();
                        // newm.notify();
                    }
                }
            }
        }
        catch(Exception xx)
            {
                return;
            }

    }
    public MeziView getaddMezi(int seq)
    {
       // MeziView newm = new MeziView();
        Rect tmprecto = new Rect();
        tmprecto = PageS.allRect[seq];
        MeziView mezii = new MeziView(MainActivityf.this);
     //   mezii.setActivated(false);

        // mezi.setOnTouchListener(new OnTouchListener() {
        //  @Override
        // public boolean onTouch(View view, MotionEvent event) {


        //  mezi.bitmapX = 100;
        //  mezi.bitmapY = 0;
        mezii.mleft = convertWn(tmprecto.left);
        mezii.mtop = convertHn(tmprecto.top);
        mezii.mwidth = convertWn(tmprecto.width());
        mezii.mheight = convertHn(tmprecto.height());
        mezii.mRes = PageS.offArray[seq];
        mezii.type = PageS.nodeArray[seq];
        //mezii.setO
        String allCmdx = cmdheader;
       // String tmpTmp = "C1200009";
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
       // allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
      //  StringBuffer allCmd = CRC16.crc16x(allCmdx);
        // mezi.setTag(allCmd.toString());
        mezii.setId(seq + 1);
        // frame.setTag(allCmd.toString());
        // mezii.setOnTouchListener(new TouchListenerx());

        //  frame.addView(mezi,0);
        //  frame.setBackgroundResource(pagestatus.pageback);
       // frame.addView(mezii, maxC);
        frame.addView(mezii);
        maxC =  maxC + 1;
        return  mezii;

    }

    public  String getCmd(int key)
    {
        String allCmdx = cmdheader;

        String tmpTmp = "C1200009";
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);



        //mezi.setTag(allCmd.toString());
        return allCmd.toString();
    }

    int getCurSel(Rect[] allrect ,int x,int y)
    {

      //  if (tempRect.contains((int) x, (int) (y)))
        Rect tmprect = new Rect() ;
        Rect tmprecto = new Rect() ;
        int tmp = allrect.length;
        for (int w=0; w<tmp;w++)
        {
            tmprecto = convertRect(allrect[w]);
            if (tmprecto.contains(x,y))
            {
                tmprect = tmprecto;
                return  w;
            }
        }
        return  -1;
    }

    int getSlide(int x,int y,int w)
    {
        Rect allrect =  new Rect() ;
        allrect.left = 329 + (w * 403)/10;
        allrect.top = 358 - 30;
        allrect.right = 399 + (w * 403)/10 ;

        allrect.bottom = 358 + 70;
        //  if (tempRect.contains((int) x, (int) (y)))
        Rect tmprect = new Rect() ;
        Rect tmprecto = new Rect() ;
      //  int tmp = allrect.length;
      //  for (int w=0; w<tmp;w++)
      //  {
            tmprecto = convertRect(allrect);
            if (tmprecto.contains(x,y))
            {
                tmprect = tmprecto;
                return  w;
            }
       // }
        return  -1;
    }


    @Override
    protected void onDestroy() {
        // uartJni.close(fd);
//        if(uartJnit != null) {
//            uartJnit.sclose();
//        }
//
        super.onDestroy();
        if(handler!=null) {
            handler.removeCallbacks(runnable);
            handler = null;
        }

        if(uHandler!=null) {
            uHandler.removeCallbacksAndMessages(null);
            uHandler = null;
        }



        if(mHandler!=null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }

        myown = null;
        this.finish();

        if(fd!=0)
        {

            try {
                uartJnit.discon();
                uartJni.close(fd);

            }
            catch(Exception ex)
            {

            }
        }
             // uHandler.removeCallbacks(uHandler);
    }
    @Override
    protected void onPause() {
       // uartJni.close(fd);
 //       fd =  uartJnit.getInstance().fd;
       // uartJnit.sclose();
//        uartJnit.close(fd);
        super.onPause();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //  super.onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_test);
        userInfo =  getSharedPreferences("user_info",
                MODE_PRIVATE);
       // myown = this;
      myown =  new WeakReference(this);



//
//        ActionBar mybar = getActionBar();
//        if(mybar!=null) {
//            mybar.hide();
//        }

        // Example of a call to a native method
        // TextView tv = (TextView) findViewById(R.id.sample_text);
        //tv.setText(stringFromJNI());
        // gv = (GridLayout) findViewById(R.id.gridlayout1);
       frame = (myFrameLayout) findViewById(R.id.gridlayout1);

//       try {
//           PageS.setfeeds();
//           refreshui(currentPage);
//       }
//       catch(Exception ex)
//       {
//
//       }
//      //  testFeed(5);
//
//       // mServiceIntent = new Intent(this, BackService.class);
//
//      //  hideStatusBar();
//      //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
//     //   getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
////        View decorView = getWindow().getDecorView();
////     //   int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
////     //           | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
////          int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
////                  // | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY ;
////
////        decorView.setSystemUiVisibility(uiOptions);
//
////       getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
////                WindowManager.LayoutParams.FLAG_FULLSCREEN);
//
////
////       //  requestWindowFeature(Window.FEATURE_NO_TITLE);
////          ActionBar actionBar = getActionBar();
////          actionBar.hide();
//
//
//        // final MeziView mezi = new MeziView(MainActivity.this);
//
//
//       // pagestatus.setInit(currentPage);
//      // refreshui(currentPage);
//
//
//
//       // tempRect = new Rect(rconvertW(mezi.mleft) , rconvertH(mezi.mtop), rconvertW(mezi.mleft + mezi.mwidth) ,rconvertH(mezi.mtop + mezi.mheight));
//         //tempRect = new Rect(mezi.mleft , mezi.mtop, mezi.mleft + mezi.mwidth ,mezi.mtop + mezi.mheight);
//
//        // mezi.getHitRect(tempRect);
//       // mezi.getDrawingRect(tempRect);
//        //mezi.type = 0;
//        String allCmdx = cmdheader;
//
//        String tmpTmp = "C1200009";
//       // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
//        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
//        StringBuffer allCmd = CRC16.crc16x(allCmdx);
//
//
//
//       // mezi.setTag(allCmd.toString());
//        //mezi.setId(2);
//       // frame.setTag(allCmd.toString());
//      //  mezi.setOnTouchListener(new TouchListenerx());
//
//
//        // mezi.setTag();
//      //  mezi.setOnTouchListener(new TouchListenerx());
//        //  @Override
//        // public boolean onTouch(View view, MotionEvent event) {
//        //调用重绘方法
//        // mezi.invalidate();
//        //    return true;
//        //   }
//        //  });
//       // frame.addView(mezi);
//        // final MeziView mezi1 = new MeziView(MainActivity.this);
//       // MeziView mezi1 = new MeziView(MainActivity.this);
//        //为我们的萌妹子添加触摸事件监听器
//        // mezi.setOnTouchListener(new OnTouchListener() {
//        //  @Override
//        // public boolean onTouch(View view, MotionEvent event) {
//        //设置妹子显示的位置
//        DisplayMetrics dm = new DisplayMetrics();
//
//        getWindowManager().getDefaultDisplay().getMetrics(dm);
//
//
//
//        int jieh = getNavigationBarHeight(this);
////        int screenWidth = dm.widthPixels;
////
////        int screenHeight = dm.heightPixels - jieh;
//        int screenWidth = PageS.pwidth;
//        int screenHeight = PageS.pheight;
//
////        mezi1.bitmapX = 100;
////        mezi1.bitmapY = 300;
////        //  mezi1.mleft = convertW(774);
////        mezi1.mleft = convertW(113);
////        mezi1.mtop = convertH(608);
////        mezi1.mwidth = convertW(141);
////        mezi1.mheight = convertH(139);
////        mezi1.mRes = R.drawable.vido_1_on;
////        //  mezi1.type = 1;
////
////        mezi1.setTag(allCmd.toString());
////        //tempRect = new Rect(mezi1.mleft , mezi1.mtop, mezi1.mleft + mezi1.mwidth ,mezi1.mtop + mezi1.mheight);
////
////        mezi1.setId(1);
//
//       // frame
//       // mezi1.setOnTouchListener(new TouchListenerx());
//
//     //  mezi.setOnTouchListener(new OnTouchListener() {
////
////            @Override
////            public boolean onTouch(View view, MotionEvent event) {
////                //设置妹子显示的位置
////                mezi.bitmapX = event.getX();
////                mezi.bitmapY = event.getY();
////                //调用重绘方法
////                mezi.invalidate();
////                return true;
////            }
////        });
//
//
//        // Resources resources = getContext().getResources();
//        // Drawable btnDrawable = resources.getDrawable(R.drawable.a3);
//      //  frame.setBackgroundResource(R.drawable.a1);
//        //  frame.setBackground(btnDrawable)；
//
//        //frame.addView(mezi1);
//        //   frame.removeAllViews();
//        //frame.removeViewAt(1);
//
//
//        // btn.setWidth(100);
//       // btn.setText(String.valueOf(count));
//
//
//        //gv.addView(plusText, plusParams);
//        //requestWindowFeature(Window.FEATURE_NO_TITLE);
//        //int count=layout.getChildCount(); if (count-3>0)
//        // { layout.removeViewAt(count-1); } } });
////        mServiceIntent = new Intent(this, BackService.class);
////        bindService(mServiceIntent, connection, BIND_AUTO_CREATE);
////
////        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
////        mIntentFilter = new IntentFilter();
////        mIntentFilter.addAction(BackService.HEART_BEAT_ACTION);
////        mIntentFilter.addAction(BackService.MESSAGE_ACTION);
////        mIntentFilter.addAction(BackService.STATE_FAIL_ACTION);
////        mIntentFilter.addAction(BackService.STATE_SUCCESS_ACTION);
////        //
////
////        mReciver = new MessageBackReciver();
////
////        mLocalBroadcastManager.registerReceiver(mReciver, mIntentFilter);
//
//        userInfo =  getSharedPreferences("user_info",
//                MODE_PRIVATE);
//
//        testtView = new TextView(this);
//        //这里的Textview的父layout是ListView，所以要用ListView.LayoutParams
//      //  ListView.LayoutParams layoutParams = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, ListView.LayoutParams.WRAP_CONTENT);
//       // textView.setLayoutParams(layoutParams);
//        testtView.setPadding(20, 0, 20, 0);
//        testtView.setText("this is used for testing");
//        testtView.setTextColor(getResources().getColor(R.color.colorAccent));
//        testtView.setTextSize(18);
//
//
//        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
//        testtView.setLayoutParams(params);
//        this.addContentView(testtView,params);
//        testtView.setVisibility(View.INVISIBLE);
//        AsyncTaskRunner runner = new AsyncTaskRunner();
//        //String sleepTime = "10:0000000123456";
//        runner.execute();
//       // makeStatusBarTransparent(this);
//
//        hideBottomUIMenu();
    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }


    //获取手机状态栏高度
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    private int getNavigationBarHeight(Activity thisa) {
        Resources resources = thisa.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        height = 0;
        return height;
    }

    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
            //do something
            return false;
        }
        return true;
    }
    //全屏并且隐藏状态栏
    private void hideStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
    }
//    requestWindowFeature(1);
//        if (hidevirtualkey != null) {
//        getWindow().getDecorView().setSystemUiVisibility(4102);
//    }
//        if (fullscreen != null) {
//        getWindow().setFlags(1024, 1024);
//    }

    //全屏并且状态栏透明显示
    private void showStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
    }

    public int convertW(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels;
        int jieh = getNavigationBarHeight(this);
//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels - jieh;
        int screenWidth = PageS.pwidth;
        int screenHeight = PageS.pheight;

        int newx = oldx * screenWidth / 2048;

        return newx;

    }

    public  Rect convertRect(Rect old)
    {
        return  new Rect(convertWn(old.left),convertHn(old.top),convertWn(old.right),convertHn(old.bottom));
    }
    public int convertH(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels;
        int jieh = getNavigationBarHeight(this);
      //  int screenWidth = dm.widthPixels;
        int screenWidth = PageS.pwidth;
        int screenHeight = PageS.pheight;

//        int screenHeight = dm.heightPixels - jieh;
//
        int newx = (old * screenHeight) / 1536;

        return newx;

    }

    protected int rconvertW(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels;
        int jieh = getNavigationBarHeight(this);
//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels - jieh;
        int screenWidth = PageS.pwidth;
        int screenHeight = PageS.pheight;

        int newx = (oldx *  2048) / screenWidth;

        return newx;

    }

    protected int rconvertH(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels;
        int jieh = getNavigationBarHeight(this);
//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels - jieh;
        int screenWidth = PageS.pwidth;
        int screenHeight = PageS.pheight;

        int newx = (1536 * old) / screenHeight;

        return newx;

    }

    protected View createButton(int index) {
        final Button btn = new Button(this);
        btn.setId(index++);
        Log.d("da", "id is" + btn.getId());

        btn.setWidth(40);
        btn.setHeight(100);
        //GridLayout.LayoutParams mParams = new GridLayout.LayoutParams(
        //btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
        //       LinearLayout.LayoutParams.WRAP_CONTENT));
        // btn.set
        // btn.setLayoutParams(new GridLayout.LayoutParams(GridLayout.LayoutParams.MATCH_PARENT, GridLayout.LayoutParams.MATCH_PARENT));
        btn.setText("okc");
        return btn;
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    // Used to load the 'native-lib' library on application startup.
    static {
        //       System.loadLibrary("native-lib");
    }


    private boolean isTouchPointInView(View view, int x, int y) {
        if (view == null) {
            return false;
        }
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int left = location[0];
        int top = location[1];
        int right = left + view.getMeasuredWidth();
        int bottom = top + view.getMeasuredHeight();
        //view.isClickable() &&
        if (y >= top && y <= bottom && x >= left
                && x <= right) {
            return true;
        }
        return false;
    }



    @Override
    protected void onStart() {
        super.onStart();
       // mClient.connect();
        userInfo.registerOnSharedPreferenceChangeListener(mListener);

    }

    @Override
    protected void onStop() {
        userInfo.unregisterOnSharedPreferenceChangeListener(mListener);
        super.onStop();
        if (!isAppOnForeground()) {
            //app 进入后台

            PageS.isActive = false;
            //全局变量isActive = false 记录当前已经进入后台
        }
    }

    public int readFeedback() {
        String tmpstr = "";
        String feedCamdstr = "";
        String feedCamdFalgstr = "";
        try {
            int read_count = uartJni.read(fd, read_buf, read_buf.length);
            if ((read_count < 0)||(read_count > 60)) {
                read_count = 0; }
            tmpstr = toHex(read_buf, read_count).toString();
            if (!tmpstr.equals("")) {
            Message cmdmsg = new Message();
            cmdmsg.what = 1;
            Bundle bcmd = new Bundle();
            int index, index82, index5a;
            int cmdlenght,feedCamdstrlenght,head;
            int tmpstrlenght = read_buf.length;
                index=index5a = tmpstr.indexOf("5aa5");
                index82 = tmpstr.indexOf("82");
                if(( index != -1) &&(index5a == index82-6)) {
                        cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
                    feedCamdstrlenght=(cmdlenght + 3) * 2;
                    if(tmpstr.length()>=feedCamdstrlenght) {
                        feedCamdstr = tmpstr.substring(index, index + feedCamdstrlenght);
                        bcmd.putString("alltext", feedCamdstr);
                        cmdmsg.setData(bcmd);
                        boolean xx = uHandler.sendMessage(cmdmsg);
                    }
                  }
        /*    index = tmpstr.indexOf("82");
            if (index >= 6) {
                index = index-6;
                if(index != -1){
                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
                    feedCamdstr = tmpstr.substring(index, index + (cmdlenght + 3) * 2);
                    bcmd.putString("alltext", feedCamdstr);
                    cmdmsg.setData(bcmd);
                    boolean xx = uHandler.sendMessage(cmdmsg);
                }
            }*/
        }
    } catch (Exception ex) {
            renew();
    }
      //  handler.postDelayed(runnable,100); // readFeedback();//
        return 1;
    }

    public void readFeedbacko() {
        String tmpstr = "";
        String feedCamdstr = "";
        String feedCamdFalgstr = "";
        try {
            int read_count = uartJni.read(fd, read_buf, read_buf.length);
            if (read_count < 0) {
                read_count = 0; }
            if (read_count > 60) {
                read_count = 60;  }
            tmpstr = toHex(read_buf, read_count).toString();
        } catch (Exception ex) {
        }
        if (!tmpstr.equals("")) {
            Message cmdmsg = new Message();
            cmdmsg.what = 1;
            Bundle bcmd = new Bundle();
            int index, index82, index5a;
            int cmdlenght;
            int tmpstrlenght = read_buf.length;

            index = tmpstr.indexOf("82");
            if (index >= 6) {
                index = index-6;
                if (index != -1) {
                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
                    feedCamdstr = tmpstr.substring(index, index + (cmdlenght + 3) * 2);
                    bcmd.putString("alltext", feedCamdstr);
                    cmdmsg.setData(bcmd);
                    boolean xx = uHandler.sendMessage(cmdmsg);
                }
            }
        }
        // handler.postDelayed(runnable,100); // readFeedback();//
        // return 1;
    }


    @Override
    protected void onResume(){
        super.onResume();


        if(fd==0) {

            fd = uartJnit.getInstance().fd;
        }

        if (!PageS.isActive) {
            //   app 从后台唤醒，进入前台

            PageS.isActive = true;
        }

        if(PageS.isActive) {


        }


        handler.postDelayed(runnable, 100);

        try {
              PageS.setfeeds();
            refreshui(currentPage);



            String allCmdx = cmdheader;

            String tmpTmp = "C1200009";
            // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
            allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
            StringBuffer allCmd = CRC16.crc16x(allCmdx);


            DisplayMetrics dm = new DisplayMetrics();

            getWindowManager().getDefaultDisplay().getMetrics(dm);



            int jieh = getNavigationBarHeight(this);
//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels - jieh;
            int screenWidth = PageS.pwidth;
            int screenHeight = PageS.pheight;

//            testtView = new TextView(this);
//
//            testtView.setPadding(20, 0, 20, 0);
//            testtView.setText("this is used for testing");
//            testtView.setTextColor(getResources().getColor(R.color.colorAccent));
//            testtView.setTextSize(18);
//
//
//            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
//            testtView.setLayoutParams(params);
//            this.addContentView(testtView,params);
//            testtView.setVisibility(View.INVISIBLE);
          //  AsyncTaskRunner runner = new AsyncTaskRunner();
            //String sleepTime = "10:0000000123456";
          //  runner.execute();
            // makeStatusBarTransparent(this);

            hideBottomUIMenu();

            reciteallui("");

           // BC 10 00 00
          //  sendStart("BC100000");
        }
        catch(Exception ex)
        {
            renew();
        }



    }

    private  final  Runnable runnable=new Runnable() {
        @Override
        public void run() {

         //   MainActivityf myown =mActivity.get();

            if (myown != null) {
                readFeedback();
            }
        }


    };

    private void renew()
    {
      //  refreshui(PageS.pageno);
      //  reciteallui("");

        return;
    }


    private class TouchListenerx implements View.OnTouchListener {
        private boolean longClicked;
        private boolean upClicked;
        private int downtimes = 0;
        private int uptimes = 0;
        private int failTime;
        //private IBackService xBackService;
//        private TouchListenerx(IBackService abak) {
//         //   xBackService = abak;
//        }

        private TouchListenerx() {
            //   xBackService = abak;
        }


//        public boolean dispatchTouchEvent(MotionEvent event) {
//            if (this != null && this.onTouch(this, event)) {
//
//
//
//
//                return true;
//            }
//            return onTouchEvent(event);
//        }


        public void okD(String cmdOne,int ttt)
        {
            Message msg = new Message();
            //  if (isSend) {
            msg.what = ttt;
            msg.obj = cmdOne;
            Bundle bundle = new Bundle();
            bundle.putString("jmppageno", cmdOne);
//                    bundle.putString("feedStatus", deviceStaus);
            msg.setData(bundle);
            //  Integer.parseInt(pagestatus.cmdArray[1]);
            mHandler.sendMessage(msg);
        }

//        public boolean onTouch(View v, MotionEvent event) {
//
//            //  iBackService.
//            int x = (int) event.getX();
//            int y = (int) event.getY();
//            currentPosition = getCurSel(PageS.allRect,x,y);
//            // final String cmdAll = v.getTag().toString();
//            // int selno = getCurSel(pagestatus.allRect,x,y)
//            //  String cmdAll = pagestatus.cmdArray[currentPosition];
//
//            //   final String cmd = cmdAll.substring(0, 22);
//
//            //int selno = pagestatus
//
//            // testFeed(6);
//            // jmpPostion = pagestatus.cmdArray[currentPosition];
//            Log.e("touchTAG", "view:"  + v.getId());
//            // int x = (int) event.getRawX();
//            // int y = (int) event.getRawY();
//            //  Rect tmpRect = new Rect();
//            //          v.getHitRect(tmpRect);
//
//            if(currentPosition!=-1){
//                String cmdOne = PageS.cmdArray[currentPosition];
//                int mmtype = pagestatus.typeArray[currentPosition];
//
//
//                // pageS.
//                if (mmtype == 20)
//                {
//                    //   okD(currentPosition + "",4);
//                    //放于cmd数组 双重健壮性检查
//                    // refreshui(1);
//                    //发消息更新界面
//                    // return true;
//                    Message msg = new Message();
//                    //  if (isSend) {
//                    msg.what = 3;
//                    msg.obj = cmdOne;
//                    Bundle bundle = new Bundle();
//                    bundle.putString("jmppageno", cmdOne);
////                    bundle.putString("feedStatus", deviceStaus);
//                    msg.setData(bundle);
//                    //  Integer.parseInt(pagestatus.cmdArray[1]);
//                    mHandler.sendMessage(msg);
//                    return  true;
//                }
//                // final String cmd = cmdAll.substring(0, 22);
//                //-1
//                // if (isTouchPointInView(v, x, y)) {
//                // if (tempRect.contains((int) x, (int) (y))) {
//                //  iosInterceptFlag = true;
//                //   return super.dispatchTouchEvent(ev);
//
//                //do
//                //  event.getY
//
//                //cmd = cmdAll.substring(0, 22);
//                // pagestatus.cmdArray[currentPosition];
//                String origin = "5AA50883192001001F"; //19E2
//                String allCmdx = cmdheader;
//                // String tmpTmp = "C1200009";
//                String tmpTmp = cmdOne;
//                // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
//                allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
//                StringBuffer allCmd = CRC16.crc16x(allCmdx);
//                final String cmd = allCmd.substring(0,22);
//                // String crcString = "83192001001F";
//                //  String crcString =  pagestatus.cmdArray[currentPosition];
//                //  String nexts = "5aa5078200030000ac1e";
//                // String crcString = cmdOne ;
//                //   StringBuffer exCmd = CRC16.crc16(crcString);
//
//
//                longClicked = false;
//                upClicked = false;
//                if (event.getAction() == 0) {
//                    // okD(currentPosition + "",7);
//
//                    testsFeed(currentPosition,true);
//                    new Thread() {
//                        public void run() {
//                            super.run();
//
//
//                            if (!longClicked) {
//                                try {
//                                    //   if (uartJint != null) {
//                                    boolean isSendx = false;
//                                    if (downtimes < 1) {
//                                        downtimes = downtimes++;
//                                        isSendx = uartJnit.getInstance().sendCmds(cmd);
//
//                                        longClicked = true;
//                                    }
//
//                                    Log.e("send TAG", "send down: " + cmd);
//                                    Message msg = new Message();
//                                    if (isSendx) {
//                                        msg.what = 1;
//
//                                        longClicked = true;
//
//
//                                        Log.e("send TAG", "send down" + cmd + "success");
//                                    } else {
//
//
//                                        Log.e("TAG", "send down  :" + cmd + "failed!");
////
//                                    }
//                                    //    }
////
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                                try {
//                                    Thread.sleep((long) TIMER_INTERVAL);
//                                } catch (InterruptedException e2) {
//                                    e2.printStackTrace();
//
//                                }
//                            }
//
//                        }
//                    }.start();
//                } else if (event.getAction() == 1) {
//                    {
//
//                        //  okD(currentPosition + "",8);
//                        testsFeed(currentPosition,false);
//                        new Thread() {
//                            public void run() {
//                                super.run();
//
//
//                                if (!upClicked) {
//                                    String tmp = cmd.substring(10, 11);
//                                    if (tmp.equals("2")) {
//
//                                        try {
//                                            //getExchangeCmd()
//
//                                            //          if ((iBackService != null) && (cmd.length() == 22)) {
//                                            if (cmd.length() == 22) {
//
//                                                boolean isSendy = false;
//
//                                                Log.e("TAG", "send  dian:" + TransformUtils.getExchangeCmd(cmd));
//
//                                                if (uptimes < 1) {
//                                                    uptimes = uptimes++;
//                                                    isSendy = uartJnit.getInstance().sendCmds(TransformUtils.getExchangeCmd(cmd));
//
//                                                    upClicked = true;
//                                                }
//                                                Message msg = new Message();
//                                                if (isSendy) {
//                                                    msg.what = 1;
//                                                    msg.obj = currentPosition;
//
//                                                    upClicked = true;
//
//
//                                                    Log.e("TAG", "send dian:" + cmd + "success");
//                                                } else {
//
//
//                                                    Log.e("TAG", "send dian " + cmd + " failed!");
//
//                                                }
//
//                                            }
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//                                    }
//                                }
//                            }
//                        }.start();
//
//                        try {
//                            Thread.sleep((long) TIMER_INTERVAL);
//                        } catch (InterruptedException e2) {
//                            e2.printStackTrace();
//
//                        }
//
//                    }
//
//                    //return true;
//                }
//            }
//
//            return  true;
//        }
//    }

        public boolean onTouch(View v, MotionEvent event) {

            try {
                int x = (int) event.getX();
                int y = (int) event.getY();

                if(!uartJnit.isFastClick())
                {
                    return true;

                }
                currentPosition = getCurSel(PageS.allRect, x, y);

                if((PageS.pageno ==0)&&(currentPosition == 4))
                {
                    isdengpressed = 1;
                }

                Log.e("touchTAG", "view:" + v.getId());


                // int curslide = getSlide(PageS.allRects, x, y);

//                int w = 0;
//                if (seekBar != null) {
//                    w = seekBar.getProgress();
//                    w = w / 10;
//                }
//                int curslide = getSlide(x, y, w);
//                if ((curslide != -1) && (isSel == 0)) {
//                    isSel++;
//                    Message msg = new Message();
//                    //  if (isSend) {
//                    msg.what = 7;
//                    // int ppp = seekBar.getProgress();
//                    // cmdOne = s
//                    msg.obj = "cmdOne";
//                    Bundle bundle = new Bundle();
//                    bundle.putInt("whichno", w);
////                    bundle.putString("feedStatus", deviceStaus);
//                    msg.setData(bundle);
//                    //  Integer.parseInt(pagestatus.cmdArray[1]);
//                    mHandler.sendMessage(msg);
//                    return true;
//                }

                if ((currentPosition != -1) && (isSel == 0)) {
                    isSel++;
                    String cmdOne = PageS.cmdArray[currentPosition];
                    int mmtype = pagestatus.typeArray[currentPosition];


                    if (mmtype == 20) {
                        Message msg = new Message();

                        msg.what = 3;
                        msg.obj = cmdOne;
                        Bundle bundle = new Bundle();
                        bundle.putString("jmppageno", cmdOne);

                        msg.setData(bundle);

                        mHandler.sendMessage(msg);
                        return true;
                    }

                    String origin = "5AA50883192001001F"; //19E2
                    String allCmdx = cmdheader;

                    String tmpTmp = cmdOne;

                    allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
                    StringBuffer allCmd = CRC16.crc16x(allCmdx);
                    final String cmd = allCmd.substring(0, 22);

                    longClicked = false;
                    upClicked = false;
                    if (event.getAction() == 0) {

                        isDown = 1;
                        // testsoFeed(currentPosition, true);
//                        Message msg = new Message();
//                        msg.what = 8;
//                        msg.obj = "cmdOne8";
//                        Bundle bundle = new Bundle();
//                        bundle.putInt("which", currentPosition);
//                        bundle.putBoolean("ifif",true);
////                    bundle.putString("feedStatus", deviceStaus);
//                        msg.setData(bundle);
//                        //  Integer.parseInt(pagestatus.cmdArray[1]);
//                        mHandler.sendMessage(msg);
//
//                        new Handler().postDelayed(new Runnable(){
//                                      public void run() {
//                                        isCal++;
//                                                      }
//                            },TIMER_INTERVAL1);
                       // isDown = 1;
                       // isUp = 0;
                      //  isMove = 0;
//                        try {
//                            Thread.sleep((long) TIMER_INTERVAL1);
//                        } catch (InterruptedException e2) {
//                            e2.printStackTrace();
//
//                        }
                        new Thread() {
                            public void run() {
                                super.run();


                                if (!longClicked) {
                                    try {
                                        //   if (uartJint != null) {
                                        boolean isSendx = false;
                                        if (downtimes < 1) {
                                            downtimes = downtimes++;
                                            isSendx = uartJnit.getInstance().sendCmds(cmd);

                                            longClicked = true;
                                        }

                                        Log.e("send TAG", "send down: " + cmd);
                                        Message msg = new Message();
                                        if (isSendx) {
                                            msg.what = 1;

                                            longClicked = true;

                                           // readFeedbacko();

                                            Log.e("send TAG", "send down" + cmd + "success");
                                        } else {


                                            Log.e("TAG", "send down  :" + cmd + "failed!");
//
                                        }
                                        //    }
//
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    try {
                                        Thread.sleep((long) TIMER_INTERVAL);
                                    } catch (InterruptedException e2) {
                                        e2.printStackTrace();

                                    }
                                }

                            }
                        }.start();

                       // return true;

                    } else {
                        if (event.getAction() == 1) {
                            {

                                Log.e("upupup",isMove +"");
                                isUp = 1;
                                isDown = 0;
                            //    isMove = 0;
                                //  okD(currentPosition + "",8);
//                                Message msg = new Message();
//                                msg.what = 8;
//                                msg.obj = "cmdOne8";
//                                Bundle bundle = new Bundle();
//                                bundle.putInt("which", currentPosition);
//                                bundle.putBoolean("ifif",false);
////                    bundle.putString("feedStatus", deviceStaus);
//                                msg.setData(bundle);
//                                //  Integer.parseInt(pagestatus.cmdArray[1]);
//                                mHandler.sendMessage(msg);
                               // isDown = 0;
                               // testsoFeed(currentPosition, false);
                                new Thread() {
                                    public void run() {
                                        super.run();


                                        if (!upClicked) {
                                            String tmp = cmd.substring(10, 11);
                                            if (tmp.equals("2")) {

                                                try {
                                                    //getExchangeCmd()

                                                    //          if ((iBackService != null) && (cmd.length() == 22)) {
                                                    if (cmd.length() == 22) {

                                                        boolean isSendy = false;

                                                        Log.e("TAG", "send  dian:" + TransformUtils.getExchangeCmd(cmd));

                                                        if (uptimes < 1) {
                                                            uptimes = uptimes++;
                                                            isSendy = uartJnit.getInstance().sendCmds(TransformUtils.getExchangeCmd(cmd));

                                                            upClicked = true;
                                                        }
                                                        Message msg = new Message();
                                                        if (isSendy) {
                                                            msg.what = 1;
                                                            msg.obj = currentPosition;

                                                            upClicked = true;

                                                            //readFeedback();
                                                            Log.e("TAG", "send dian:" + cmd + "success");
                                                        } else {


                                                            Log.e("TAG", "send dian " + cmd + " failed!");

                                                        }

                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }
                                    }
                                }.start();

                                try {
                                    Thread.sleep((long) TIMER_INTERVAL);
                                } catch (InterruptedException e2) {
                                    e2.printStackTrace();

                                }

                            }
                            handler.postDelayed(runnable,100);
                            //return false;
                        }
                        else if (event.getAction() == 2) {
                            Log.e("movemove:",isDown +"");
                            if(isDown == 1) {
                                Log.e("many times:",isCal +"");
                               // isMove ++;
//                                if(isMove > 0)
//                                {
//                                    new Handler().postDelayed(new Runnable(){
//                                        public void run(){
//                                            //execute the task
//
//
//                                           // if(isUp == 0)
//                                           // {
//                                                Message msg = new Message();
//                                                msg.what = 8;
//                                                msg.obj = "cmdOne8";
//                                                Bundle bundle = new Bundle();
//                                                bundle.putInt("which", currentPosition);
//                                                bundle.putBoolean("ifif",false);
////                    bundle.putString("feedStatus", deviceStaus);
//                                                msg.setData(bundle);
//                                                //  Integer.parseInt(pagestatus.cmdArray[1]);
//                                                mHandler.sendMessage(msg);
//
//                                           // }
//                                        }
//                                    },TIMER_INTERVAL1);
//
//
//                                    Message msg = new Message();
//                                msg.what = 8;
//                                msg.obj = "cmdOne8";
//                                Bundle bundle = new Bundle();
//                                bundle.putInt("which", currentPosition);
//                                bundle.putBoolean("ifif",false);
////                    bundle.putString("feedStatus", deviceStaus);
//                                msg.setData(bundle);
//                                //  Integer.parseInt(pagestatus.cmdArray[1]);
//                                mHandler.sendMessage(msg);
//                               // isMove = 0;
                                }
                            //testsoFeed(currentPosition, false);
//                                                        new Handler().postDelayed(new Runnable(){
//                            public void run(){
//                               // execute the task
//                               // testsoFeed(currentPosition, false);
//                                Message msg = new Message();
//                                msg.what = 8;
//                                msg.obj = "cmdOne8";
//                                Bundle bundle = new Bundle();
//                                bundle.putInt("which", currentPosition);
//                                bundle.putBoolean("ifif",false);
////                    bundle.putString("feedStatus", deviceStaus);
//                                msg.setData(bundle);
//                                //  Integer.parseInt(pagestatus.cmdArray[1]);
//                                mHandler.sendMessage(msg);
//                            }
//                        },50);

//                                Message msg = new Message();
//                                msg.what = 8;
//                                msg.obj = "cmdOne8";
//                                Bundle bundle = new Bundle();
//                                bundle.putInt("which", currentPosition);
//                                bundle.putBoolean("ifif",false);
////                    bundle.putString("feedStatus", deviceStaus);
//                                msg.setData(bundle);
//                                //  Integer.parseInt(pagestatus.cmdArray[1]);
//                                mHandler.sendMessage(msg);
                           // isDown = 0;
                          // return true;
                       }

                        }
                    }
//                    else if (event.getAction() == 2) {
//
////                        new Handler().postDelayed(new Runnable(){
////                            public void run(){
////                                //execute the task
////                                testsoFeed(currentPosition, false);
////                            }
////                        },100);
//
//
////                       if(isDown == 1) {
////                           testsoFeed(currentPosition, false);
////                       }
//
//                        return false;
//                    }
//                    else if (event.getAction() == 4) {
//                        // testsoFeed(currentPosition, false);
//                         return false;
//                    }
                        //          }

                        if (isSel > 0) isSel = 0;
                    }


            catch(Exception ex)
                    {

                    }

                    // return true;
                    return false;
                }

            }



            private void sendStart(String cmdOne)
            {
                String origin = "5AA50883192001001F"; //19E2
                String allCmdx = cmdheader;

                String tmpTmp = cmdOne;

                allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
                StringBuffer allCmd = CRC16.crc16x(allCmdx);
                final String cmd = allCmd.substring(0, 22);
                boolean isSendst = false;
                isSendst = uartJnit.getInstance().sendCmds(cmd);
                if (isSendst) {


                    Log.e("send start TAG", "send start " + cmd + " success");
                } else {
                    Log.e("send start TAG", "send start " + cmd + " failed!");
                }

            }

     private void psendStart(String cmdOne)
     {
         String origin = "5AA50883192001001F"; //19E2
         String allCmdx = cmdheader;

         String tmpTmp = cmdOne;

         allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
         StringBuffer allCmd = CRC16.crc16x(allCmdx);
         final String cmd = allCmd.substring(0, 22);
         boolean isSendst = false;
         isSendst = uartJnit.getInstance().sendCmds(cmdOne);
         if (isSendst) {


             Log.e("send start TAG", "send pstart " + cmdOne + " success");
         } else {
             Log.e("send start TAG", "send pstart " + cmdOne + " failed!");
         }

     }


     public static String toHex(byte[] buffer,int read_count) {
        StringBuffer sb = new StringBuffer(read_count * 2);
        for (int i = 0; i < read_count; i++) {
            sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 15, 16));
        }
        return sb.toString();
    }

private class AsyncTaskRunner extends AsyncTask<Void,  String, Void> {

    private String resp;
    ProgressDialog progressDialog;
    LocalServerSocket serverSocket;

    @Override
    protected Void doInBackground(Void... params) {
       // publishProgress("Sleeping..."); // Calls onProgressUpdate()

          //  for(;;){

                    try {
                        //socketAddress需跟localSocket地址一致，否则无法连接上

                        serverSocket = new LocalServerSocket(SOCKET_ADDRESS);

                       // LocalSocket receiveSocket = serverSocket.accept();


                        //设置缓冲大小
                      //  receiveSocket.setReceiveBufferSize(256*4);


                        BufferedReader reader;
                        String message;
                        //final StringBuffer buffer;
                        String line = "";
                        while (true) {



                            LocalSocket accept = serverSocket.accept();
                            InputStream ips = accept.getInputStream();
                            ByteArrayOutputStream byteOps = new ByteArrayOutputStream();
                            byte[] buf = new byte[1024];
                            int len = -1;
                            while((len = ips.read(buf)) != -1){
                                byteOps.write(buf, 0, len);
                            }

                            byte[] array = byteOps.toByteArray();
                            String msg = new String(array);
                          //  showToat(msg);
                            ips.close();
                            accept.close();



                            publishProgress(msg);
                        }

                      //  publishProgress(); // Invokes onProgressUpdate()
                        //localSocket.setSendBufferSize(ConstantConfig.BUFFER_SIZE);
                    } catch (Exception e) {
                        e.printStackTrace();
                       // LoggerHelper.d("Waiting to be linked to a bug,error:" + e.toString());
                      //  return false;
                    }




            return null;
    }


    @Override
    protected void onPostExecute(Void result) {
        // execution of result of Long time consuming operation
       //progressDialog.dismiss();
      //  finalResult.setText(result);
     //   testView.setText("finished");
    }


    @Override
    protected void onPreExecute() {
      //  progressDialog = ProgressDialog.show(MainActivity.this,
      //          "ProgressDialog",
      //          "Wait for "+time.getText().toString()+ " seconds");
        resp = "TransformUtils.comingdata";
    }


    @Override
    protected void onProgressUpdate(String... values) {
       // String msg = userInfo.getString("user_info", "0000");


        // testView.setText(text[0]);
       // String msgsource = TransformUtils.comingdata;
       // String firstFour = msgsource.substring(0, 25);
             testView.setText(values[0]);
      //  testView.setText(text[0]);
        // Things to be done while execution of long running operation is in
        // progress. For example updating ProgessDialog
    }
}

    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }
}